<?php

$res = mysql_query ("SELECT p.Id AS pid, p.PageId, p.Link, p.Title, p.Public, u.Username, ups.UserId as uid 
	FROM page AS p 
	LEFT OUTER JOIN user_page_submission AS ups ON p.Id = ups.PageId 
	LEFT OUTER JOIN user AS u ON ups.UserId = u.Id 
	WHERE p.Id = '$id' 
	GROUP BY p.Id  ") or die ("error");

if (mysql_num_rows ($res) != 1 ) {
?>
<script type="text/javascript">
window.location = '?page=pages_non';
</script>
<?php	

}

$row = mysql_fetch_array ($res);
extract ($row);
if (isset ($PageId)) {
	$url = 'http://graph.facebook.com/';
	$pageUrl = "" . $url . $PageId . "";
	// create curl resource
	$ch = curl_init();
	// set url
	curl_setopt($ch, CURLOPT_URL, $pageUrl);
	curl_setopt($ch,CURLOPT_HTTPHEADER,array ("Content-Type: text/xml; charset=utf-8"));
	//return the transfer as a string
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	// $output contains the output string
	$output = curl_exec($ch);
	//$output = utf8_encode($output);
	//echo $output . "<br />";

	$param = json_decode($output, true);
	
	$Link = $param['link'];
	$Title = $param['name'];
	$Image = $param['picture'];
	$Fans = $param['fan_count'];
	$Category = str_replace('_', ' ', $param['category']);
}

///////////////////// VERIFY
if (isset($_SESSION['id']) and isset($_GET['id']) and $_GET['mes']=='add') {
	$res = mysql_query ("UPDATE page SET Link='$Link', Title='$Title', Image='$Image', Category='$Category', Updated=CURRENT_TIMESTAMP, Verified = 1 WHERE Id = '$id' ");

	// INSERT NOTE
	$note = "Page is indexed. Waiting for data.";
	$res = mysql_query ("INSERT INTO note (PageId, Content) VALUES ('$id', '$note') ");
	$noteId = mysql_insert_id();

	// INSERT USER_PAGE_NOTE
	$query = "SELECT UserId FROM user_page_submission WHERE PageId = '$id' ";
	$res = mysql_query ($query);
	$nr = mysql_num_rows ($res);
	while ($nr > 0) {
		$row = mysql_fetch_array ($res);
		extract ($row);
		$us_id = $UserId;
		mysql_query ("INSERT INTO user_note (UserId, NoteId) VALUES ('$us_id', '$noteId') ");	
		
		$nr--;
	}
	
	?>
    <script type="text/javascript">
	window.location = '?page=pages_non';
	</script>
    <?php
	//echo $userId . " | " . $pageId . " | " . $_GET['mes'];
}

?>

<style>
		body { font-size: 62.5%; }
		label, input { display:block; margin:5px 0px 0px 0px; width:300px; }
		/*input.text { margin-bottom:12px; width:95%; padding: .4em; }*/
		fieldset { padding:0; border:0; margin-top:20px; }
		h1 { font-size: 1.2em; margin: .6em 0; }
		div#users-contain { width: 350px; margin: 20px 0; }
		div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
		div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
		.ui-dialog .ui-state-error { padding: 0px 0px 0px 5px; }
		.validateTips { border: 1px solid transparent; padding: 0.3em; }
	</style>
	<script>

	$(function() {
		// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
		
		var title = $( "#title" ),
			pagelink = $( "#pagelink" ),
			pid = $( "#pid" ),
			ispublic = $( "#ispublic" ),
			allFields = $( [] ).add( title ).add( pagelink ).add( pid ).add( ispublic ),
			tips = $( ".validateTips" );

		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );
		}

		function checkLength( o1, o2, o3, min) {
			if ( o1.val().length < min &&  o2.val().length < min  &&  o3.val().length < min ) {
				//o1.addClass( "ui-state-error" );
				updateTips( "Please submit either of page details." );
				return false;
			} else {
				return true;
			}
		}

		function checkRegexp( o, regexp, n ) {
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			} else {
				return true;
			}
		}
		function isUrl(s) {
			var regexp = /(http):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
			return regexp.test(s);
}

		$( "#dialog-form" ).dialog({
			autoOpen: false,
			height: 300,
			width: 350,
			modal: true,
			resizable: false,
			buttons: {
				"Update page": function() {
					var bValid = true;
					allFields.removeClass( "ui-state-error" );

					bValid = checkLength( title, pagelink, pid, 1 );

					if (pid.val().length > 0) {
						bValid = bValid && checkRegexp( pid, /^([0-9])+$/, "Page Id is not number" );
					}
					if (pagelink.val().length > 0) {
						bValid = bValid && checkRegexp( pagelink, /(http:\/\/|www)(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/, "Page Link is not valid. Must begin with http:// or www." );
					}
					if (title.val().length > 0) {
						bValid = bValid && checkRegexp( title, /^[a-z]([0-9a-z_|\.\- ])+$/i, "Title may consist of a-z, spaces, 0-9, '_ | . ,' begin with a letter." );
						// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
					}
					
					if ( bValid ) {
						// INSERT PAGE
						// CREATE NOTE
						
						xmlhttp = new XMLHttpRequest();
						xmlhttp.open("POST","ajax/update_page.php",true);
						xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
						xmlhttp.send("pid="+pid.val()+"&title="+title.val()+"&link="+pagelink.val()+"&public="+ispublic.val()+"&id=<?php echo $id; ?>");
						
						xmlhttp.onreadystatechange=function() {
  							if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    							if (xmlhttp.responseText == "success") {
									//updateTips (xmlhttp.responseText);
									$( this ).dialog( "close" );				
									$( "#dialog-message" ).dialog( "open" );
								}
							}
						}
						
						// title.val()
						// pagelink.val() 
						// pid.val() 
						//$( this ).dialog( "close" );
					}
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
		
		$( "#dialog-message" ).dialog({
			autoOpen: false,
			height: 300,
			width: 350,
			modal: true,
			resizable: false,
			buttons: {
				Ok: function() {
					$( "#dialog-form" ).dialog( "close" );
					$( this ).dialog( "close" );
				}
			}
		});

		$( "#create_page" )
			.button()
			.click(function() {
				$( "#dialog-form" ).dialog( "open" );
			});
	});
	
	</script>


 <div id="content">

<div class="huge_box">
<?php include ("components/page_tabs.php"); ?>
<div class="huge_box_header">
<div class="title">Page Verification</div>
</div>

<div class="huge_box_item">
	
	<div class="avatar">
    <img src="<?php echo $Image; ?>" alt="<?php echo $Title; ?>" width="50px" height="50px" />
    </div>
	<div class="description">
	PageId: <?php echo $PageId; ?><br />
    Link: <a href="<?php echo $Link; ?>" target="_blank"><?php echo $Link; ?></a><br />
 	Title: <?php echo $Title; ?><br />
    Submitted by: <?php echo $Username; ?>
    </div>	
    
    <div style="float:right; padding:12px 0px 12px 0px">
	<button id="create_page">Update Page</button>
	<a href="?page=page_non&mes=add&id=<?php echo $id;?>">Verify Page</a></button>	
    </div>
</div>

</div>


</div>


<div id="dialog-form" title="Update page details">
	<p class="validateTips">Please update page details.</p>
	<form>
	<fieldset>
		<label for="pid">Page Id</label>
		<input type="text" name="pid" id="pid" value="<?php echo $PageId; ?>" class="text ui-widget-content ui-corner-all" />
		<label for="pagelink">Page Link</label>
		<input type="text" name="pagelink" id="pagelink" value="<?php echo $Link; ?>" class="text ui-widget-content ui-corner-all" />
        <label for="title">Page Title</label>
        <input type="text" name="title" id="title" value="<?php echo $Title; ?>" class="text ui-widget-content ui-corner-all" />
        <label for="ispublic">Public</label>
        <select name="ispublic" id="ispublic" class="text ui-widget-content ui-corner-all">
        <option value="0" <?php if ($Public == 0) echo "selected=\"selected\""; ?>>No</option>
        <option value="1" <?php if ($Public == 1) echo "selected=\"selected\""; ?>>Yes</option>
        </select>		
	</fieldset>
	</form>
</div>


<div id="dialog-message" title="Page successfully updated">
	<p>Page details are successfully updated.<br /><br />
Thank You!</p>
</div>

