function alertInput(id, offset) {
	$(id).css({ "background-color":"red"});
	$(id).click(function() { $(id).css({ "background-color":"white"}); });
	scroll(0,offset);
}

$(document).ready(function() {
function makeReview(obj, item) {
	
	var text = '<div id="review_'+item.rid+'">';
	text+='<div class="dateReviewed">'+item.date_reviewed+'<br>Salary: '+item.pay+'</div>';
	text+=item.position+' in '+item.location;
	text+=item.rating;
	text+='<br/><br/>';
	
	text+='<b>Pros:</b>';
	text+='<div id="pros_'+item.rid+'">'+item.pros+'</div>';
	text+='<b>Cons:</b><div id="cons_'+item.rid+'">'+item.cons+'</div>';
	text+='<b>Advice to future Interns:</b><div id="advice_'+item.rid+'">'+item.advice+'</div>';
	text+='<div class="reviewPreviewFoot">';
							
	text+='<span id="commentReview_'+item.rid+'" class="link">Discuss</span>('+item.comments+')';
	
	text+=' <span id="flagReview_'+item.rid+'" class="link">Flag</span>';
	text+=' <span id="link_'+item.rid+'" class="link">Link</span> ';
	text+='<span id="helpfulText_'+item.rid+'"><span  id="helpfulYes_'+item.rid+'" class="link">Helpful</span> or <span class="link" id="helpfulNo_'+item.rid+'">Not</span>?</span> ';
	text+='</div>';
	return text;
	}
	
	function makeListing(obj, item) {
	var text='<div id="listing_'+item.id+'">';
	text += '<div class="dateReviewed">'+item.date_posted+'</div>';
	text += '<b>Position:</b>'+item.position+' <br> '+item.city;
	text += '<div id="majors_'+item.id+'"><b>Majors:</b><br/> ';
	var stext= '';
	$.each(item.majors,function(i,item){
		stext += item+', ';
	});
	text += stext.substring(0,stext.length-2);
	text += '</div>';
	text += '<b>Description:</b> ';
	text += '<br/><div id="desc_'+item.id+'">'+item.desc+'</div>';
	text += '<b>Qualifications:</b><div id="qual_'+item.id+'">'+item.qual+'</div>';
	text += '<b>Contact Information:</b><div id="contact_'+item.id+'">'+item.contact+'</div>';
	text += '<div class="reviewPreviewFoot">';
	//text += 'Discuss(0)';
	text += '</div>';
	text+= '</div>';
	return text;
	}
	function reviewSetup(obj, item) {
		$("#reviewRating_"+item.rid).stars({ disabled: true });
		trunc("#pros_"+item.rid,100); 
		trunc("#cons_"+item.rid,100); 
		trunc("#advice_"+item.rid,100); 
		//createdIds.push("#reviewRating_"+item.rid);
		//createdIds.push("#review_"+item.rid);
	}
	function listingSetup(obj, item) {
		//rightIds.push("#listing_"+item.id);
		
		trunc("#desc_"+item.id,100);
		trunc("#qual_"+item.id,100);
		trunc("#contact_"+item.id, 100);
		trunc("#majors_"+item.id, 50); 
	}
	function trunc(id, s) {
	$(id).truncate(s, {
		trail: [ " [<a href='#' class='truncate_show'>show more</a>]", " [<a href='#' class='truncate_hide'>show less</a>]" ]});
	}
	function linksSetup(item) {
	//alert("in links setup");
	$("span[id='commentReview_"+item.rid+"']").click(function(){
								//var rid = this.id.substring(this.id.indexOf("_")+1);
								$.get("newphp/data.php", 
									{ action: "getComments", type: "r", id: item.rid },
									function(data) {
								$("#dialogBox").html(data);
								$("#dialogBox").dialog( {title:"Discuss Review", width:500, beforeclose: function() { $("#dialogBox").dialog('destroy'); } });										
								
								});							
															
							});
							
							$("span[id='flagReview_"+item.rid+"']").click(function(){
								//var rid = this.id.substring(this.id.indexOf("_")+1);
							
								var html = '<p>Internlist will check this review for inappropriate content. Are you sure you want to flag?</p><br><br><center><span class="link" id="yesFlag">Yes</span></center>';
								$("#dialogBox").children().remove();
								$("#dialogBox").text("");
								$("#dialogBox").dialog({ title: "Flag Review", width:500, beforeclose: function() { $("#dialogBox").dialog('destroy'); } });
								$(html).appendTo("#dialogBox");
								
								$("#yesFlag").click( function(){
									$.get("newphp/data.php", { action: "flagReview", rid: item.rid });
									$("#dialogBox").text("Thanks. We will check it out.");
								});
							});							
							$("span[id='emailReview_"+item.rid+"']").click(function(){
								var html= 'Enter a friends email address and click to send them a link to this page.';
								html+= '<table><tr><td>Your Name</td><td><input type="text" id="name" /></td></tr><tr><td>Friends Email</td><td><input type="text" id="email" /></td></tr><tr><td>Quick Message</td><td><textarea name="msg" id="message"></textarea></td></tr></table><center><span class="link" id="sendEmail">Send</span></center>';	
								$("#dialogBox").children().remove();
								$("#dialogBox").text("");

								$("#dialogBox").dialog({ title: "Email This Page", width:500, beforeclose: function() { $("#dialogBox").dialog('destroy'); } });
								$(html).appendTo("#dialogBox");
								$("#sendEmail").click(function(){
									$.post("newphp/data.php", {action: "emailReview", page: window.location.href, from: $("#name").val(), to: $("#email").val(), message: $("#message").val() });
									$("#dialogBox").text("Your message has been sent!");
								});
							});				
										
							$("span[id='link_"+item.rid+"']").click(function(){
								 var html= '<input type="text" size="50" value="'+window.location.href+'" />';
								 html+= '</div>';
								$("#dialogBox").children().remove();
								$("#dialogBox").text("");
								
								$("#dialogBox").dialog({ title: "Permanent Link", width: 500, beforeclose: function(){ $("#dialogBox").dialog('destroy'); } });
								$(html).appendTo("#dialogBox");

							});
														
							$("span[id='helpfulYes_"+item.rid+"']").click(function(){
								var p = $(this).parent();
								$(p).fadeOut(1000, function () {
									$(p).text("Thanks!");
									$(p).fadeIn(1000);
								});	
								//var rid = this.id.substring(this.id.indexOf("_")+1);
								$.get("newphp/data.php", { action: "rateReview", rid: item.rid, value: "Yes" }); 
							});
							$("span[id='helpfulNo_"+item.rid+"']").click(function(){
								var p = $(this).parent();
								$(p).fadeOut(1000, function () {
									$(p).text("Thanks!");
									$(p).fadeIn(1000);
								});
								//var rid = this.id.substring(this.id.indexOf("_")+1);
								$.get("newphp/data.php", { action: "rateReview", rid: item.rid, value: "No"});
								
							});
	}
	
	var homeText = "Hey there. Thanks for stopping by. If you're in college, chances are you're either looking for an internship or you've already had one. If you've already interned at a company, please take a few minutes and anonymously review it. We would really appreciate it along with every other potential intern'ee out there. Otherwise, feel free to browse the review directory, search for a specific company, or look for internship listings.";
	
	$("div[id*='companyList_']").hide();
	//hash tag function
	var id=false;
	var createdIds = [];
	var rightIds = [];
	function cleanup() {
	//cleanup
		$("#rightBox").children().remove();
		$("#leftBox").children().remove();
					/*for(var i=0;i<rightIds.length;i++) {
						$(rightIds[i]).remove();
					}
					//cleanup
					for(var i=0;i<createdIds.length;i++) {
						$(createdIds[i]).remove();
					}
					*/
	}
	
	function loadHomeReviews(last) {
		$.get("newphp/data.php", 
			{ action: 'getLatestReviews', last: last },
			function(data) {
					
			var obj = json_parse(data);
			$.each(obj,function(i,item) {
				var text = '<h3 id="cname_'+item.rid+'"><a href="#!display?company='+item.cid+'">'+item.name+'</a></h3>';
				//createdIds.push("#cname_"+item.rid);
				text += makeReview(obj, item);
				$(text).appendTo("#leftBox");
				reviewSetup(obj, item); 
				$("#leftSpacer").remove();
				linksSetup(item);
			});
			leftLoadHome = true;
		});
	}
	
	function loadHomeInternships(last) {
		$.get("newphp/data.php",
		{ action: 'getLatestInternships', last: last},
		function(data) {
			var obj = json_parse(data);
			$.each(obj, function(i, item) {
				var text = '<h3 id="icname_'+item.id+'">'+item.cname+'</h3>';
				//rightIds.push("#icname_"+item.id);
				text += makeListing(obj, item);
				$(text).appendTo("#rightBox");
				listingSetup(obj, item);
			});
			rightLoadHome = true;
		});
	}
	
	function restore() {
	var h = '<h1 id="title"></h1><span id="welcomeText"></span><table id="contentTbl"><tbody><tr><td><div id="leftCol"><h2 id="leftContentCol">New Anonymous Intern Reviews</h2><div id="leftBox" class="box"></div></div><div class="box_bottom"></div></td><td><div id="rightCol"><h2 id="rightContentCol">New Internship Opportunities</h2><div id="rightBox" class="box"></div></div><div class="box_bottom"></div></td></tr></tbody></table></div>';
	$('#innerContent').html(h);
	}
	
	function reviewSummary(id) {
		$.get("newphp/data.php", 
		{ action: 'getReviewRatings',
		  id: id },
		function(data) {
			$(data).appendTo("#welcomeText");		
		});	
	}
	
	$(function() {
 		var current_hash = false;
	     setInterval(function() {
     	 	if(window.location.hash != current_hash) {			
				
	          	current_hash = window.location.hash;
				if(current_hash != -1) {	
				var pId = current_hash.lastIndexOf("=");
				id = current_hash.substring(pId+1);
				var pFunc = current_hash.indexOf("?");
				var func = current_hash.substring(1,pFunc);
				if(pId == -1)
					var target = current_hash.substring(pFunc+1);
				else	
					var target = current_hash.substring(pFunc+1, pId);
					
				if(current_hash == "#search") {
					$.post("newphp/data.php", 
					{ action: 'search',
					  term: $("#searchBox").val() },
					  function(data) {
					  	$("#innerContent").html(data);
					  });
				}
				else if(current_hash == "#!home"){
					
					var last = 0;
					var rid=0;
					cleanup();
					/*
					$.get("newphp/data.php",
						 { action: 'getHomePage' }, 
						 function(data) {
							 $("#innerContent").html(data);
						 }
					);
						 
					
					*/
					restore();
					
					$("#title").text("Welcome to Internlist");
					$("#welcomeText").text(homeText);
						try {
						loadHomeReviews(last);
						loadHomeInternships(last);
						
						
						} catch(e) {
						
						}					
				}	
				
				else if(current_hash == "#!review") {
					$.get("newphp/data.php",
					{action: 'writeReview'},
					function(data){
						$("#innerContent").html(data);
					});
				}		
				else if(current_hash == "#!recruit") {
					$.get("newphp/data.php",
					{ action: 'recruit'},
					function(data) {
						$("#innerContent").html(data);
					});
				}	
				else if(func == "expand") {
					if(target == "all") {
						$("div[id*='companyList_']").show();
					} else {
					var o = $('#companyList_'+id);
					$('#expandDirectory_'+id).attr("href", "!#collapse?directory="+id);
					o.show(400);
					}
				} 
				else if(func == "collapse") {
					if(target == "all") {
						$("div[id*='companyList_']").hide();
					} else {
					var o = $('#companyList_'+id);
					o.hide(400);
					$('#expandDirectory_'+id).attr("href", "!#expand?directory="+id);				
					}
				}
				else if(func == "!display") {
					cleanup();
					$("#innerContent").html("");
					restore();
					//alert("id:"+id);
					scroll(0,0);
					var obj = {};
					var cName = $('#company_'+id).text();
					$('#title').text(cName+" Overview");
 
					$.get("newphp/data.php",
						{action: 'getCompanyInternships', id: id},
						function(data){
						

						try {
							obj = json_parse(data);
							$.each(obj,function(i,item){
								var text = makeListing(obj, item);
								
								$(text).appendTo("#rightBox");
								listingSetup(obj,item);
								
							});
							
						} catch(e) {
							var t = '<div id="noInts">There aren\'t any internships posted for '+cName+'.</div>';
							//rightIds.push("#noInts");
							$(t).appendTo("#rightBox");
						}
					});
					$('#rightContentCol').text("Available Internships");
					document.title = "Anonymous "+cName+" Internship Reviews &amp; "+cName+" Internship Opportunities"; 
					$('#welcomeText').text("Here's what we got on "+cName+". If you know anyone who's interned here, please ask them to submit an anonymous review.");
					reviewSummary(id);

					$.get("newphp/data.php", 
						{ action: 'getCompanyReviews', id: id },  
						function(data){
							
							try {
							obj = json_parse(data);
							
							//$('#welcomeText').text(data);
							//$('#innerContent').hide();
							$('#leftContentCol').text("Anonymous Reviews");
							
							$.each(obj.review,function(i,item){		
								var text = makeReview(obj, item);
								
								$(text).appendTo("#leftBox");
								//alert(item);
								reviewSetup(obj, item);
								linksSetup(item);
								$(".stars").stars( { disabled: true });
							});
							
							} catch(e) { 
								var x = 'Sorry we don\'t have any internship reviews for '+cName+'. If you\'ve worked here please be the first to post one.';
								
								$("#welcomeText").text(x)
								var x = '<span id="noRev">No reviews available.</span>';
								$(x).appendTo("#leftBox");
							} //catch ex
							$('#innerContent').show(500);					
		
					});
					
					
				}
				else if(func == "listing") {
				
				}
				
				
				} //current hash if
				
				//$('#content').load("content.php?page="+current_hash);
          	}        
    		}, 100);    
	}); //hash tag function
	var leftLoadHome = true;
	var rightLoadHome = true;
	$(window).scroll(function(){
		var rid=0;
		var ro = $("div[id^='listing_']").last();
		var rOrigHeight = ro.height();
		
		var o = $("div[id^='review_']").last();
		var oh = o.height();
		var s = $(window).scrollTop();
		var h = $(window).height();
		//$("<div>"+(s+h)+", "+o+"</div>").appendTo("#leftBox");
		if(window.location.hash == "#!home") {
			if(leftLoadHome && s+h >= o.offset().top+oh ) { 
			leftLoadHome = false;
			//setTimeout(function(){
			rid = $("div[id^='review_']").last().attr("id");
			var p = rid.indexOf("_");
			rid = rid.substring(p+1);
			//	},10);
			if(rid > 4)
				loadHomeReviews(rid); 
		
			}
			
			if(rightLoadHome && s+h > ro.offset().top+ro.height()) {
				rightLoadHome = false;
				var id = $("div[id^='listing_']").last().attr("id");
				var p = id.indexOf("_");
				id = id.substring(p+1);
				if(id > 20)
					loadHomeInternships(id);
			}
		}		
	});	
	
     $("#stars").stars({
        inputType: "select",
	   disabled: true
     });
	
	$("#load").ajaxStart(function() {
		$(this).show();
	});
	$("#load").ajaxStop(function() {
		$(this).hide();
	});
	
	if(window.location.hash == "")
		window.location.hash = "!home";

	$("span[id^='expandAll']").click(function() {
		$("div[id^='companyList_']").show();
	});
	$("span[id^='collapseAll']").click(function() {
		$("div[id^='companyList_']").hide();
	});
	
	
	$("#searchButton").click(function () {
		window.location.hash = "!search";
	});
	
	$('#flat').menu({ 
			content: $('#flat').next().html(), // grab content from this page
			showSpeed: 400 
	});
	$('.fg-button').hover(
    		function(){ $(this).removeClass('ui-state-default').addClass('ui-state-focus'); },
    		function(){ $(this).removeClass('ui-state-focus').addClass('ui-state-default'); }
    	);
	
	function changeFilter(item) {
		alert(item.id);
	}
});
// JavaScript Document
