$(document).ready(function() {
	
	$("#please_wait").hide();
	//start of booth content switching function---------------------------------------------------------------------
	$('#booth_top_nav a').click(function () {
		$("#booth_stuff").removeClass("booth_max_height");
		
		$("#booth_top_nav").find("img").removeClass("button_select");
		$(this).find("img").addClass("button_select");
		
		var loadUrl = $(this).attr("rel") + ".php5";
		var options = { direction: "right" };
		//first make wrapper height permanent
		$("#booth_wrapper").height($("#booth_wrapper").height());
		//hide current content
		$("#booth_stuff").hide("slide", options, 1000, function () {
			//shrink wrapper to loading screen size
			$("#booth_wrapper").animate({ height: "70px" }, 1000);
			//display loading screen
			$("#please_wait").fadeIn(1000, function () {
				$("#booth_stuff").load(loadUrl, null, function(responseText){ 
					//expand wrapper to new height
					var new_height = $("#booth_stuff").height();
					if (new_height > 600 || loadUrl=="tab_map.php5" || loadUrl=="tab_twitter.php5" || loadUrl=="tab_welcome.php5" || loadUrl=="tab_pictures.php5" || loadUrl=="tab_polls.php5") { 
						new_height = 600; 
						$("#booth_stuff").addClass("booth_max_height");
					} //set maximum height
					$("#booth_wrapper").animate({ height: new_height }, 1000, null, function () {
						//hide the loading screen
						$("#please_wait").fadeOut(1000, function() {
							//bounce in the new content screen
							$("#booth_stuff").show("slide", options, 1000);
							if(loadUrl=="tab_map.php5") {
								map_load();
							} else if(loadUrl=="tab_events.php5") {
								show_calendar();
							}
						});
					});
				});
			});
		});
	});
	//end of booth content switching------------------------------------------------------------------------------------------------

	//add hover effect to tab buttons
	$("#booth_top_nav a").hover(function() {
		$(this).find("img").addClass("button_hover"); 
	}, function() {
		$(this).find("img").removeClass("button_hover");
	});

	//open basic info tab for the booth
	$("#booth_top_nav a:first").trigger('click');


	$("#leftarrow").click(function() {
		//move old booth out to the right
		$("#booth_title").hide("slide", { direction: "right" }, 1000);
		$("div.booth_box").hide("drop", { direction: "right" }, 1000, function() {
			
			//load new booth
			
			$("div.booth_box").show("drop", { direction: "left" }, 1000);
			$("#booth_title").show("slide", { direction: "left" }, 1000);
		});
	
	});
	//end of left arrow click
	
	$("#rightarrow").click(function() {
		//move old booth out to the left
		$("#booth_title").hide("slide", { direction: "left" }, 1000);
		$("div.booth_box").hide("drop", { direction: "left" }, 1000, function() {
			
			//load new booth
			
			$("div.booth_box").show("drop", { direction: "right" }, 1000);
			$("#booth_title").show("slide", { direction: "right" }, 1000);
		});
	
	});
	//end of left arrow click
		
	
	//review links
	$("a.reviewlink").click(function() {
		$("#reviewform").load("lib/reviewform.html");
		$.blockUI({ css: { 
            border: '7px solid #555', 
            padding: '15px', 
            backgroundColor: '#FFF', 
            '-webkit-border-radius': '10px', 
            '-moz-border-radius': '10px',  
            color: '#555',
			top: '3%',
			width: '570px',
			height: '400px',
			overflow: 'auto'
        }, message: $('#reviewform') }); 
		$('.blockOverlay').click($.unblockUI);
		return false;
	});
	
	//adv college search auto field
	$("#adv_search_field").focus(function () {
		$(this).attr("value", "");
	});
	//auto complete stuff
	$("#adv_search_field").blur(function(){ setTimeout("clearAutoComplete()", 200) });
	
	$("#adv_search_field").keyup(function (e) {
		var keyCode = e.keyCode || window.event.keyCode;
		var lastVal = $(this).val();
		if(adv_updownArrow(keyCode)){
			return;
		}
		if(keyCode == 13 || keyCode == 27){
			clearAutoComplete();
			return;
		}
		setTimeout(function () {adv_autoComplete(lastVal)}, acDelay);
	});
	
	//advanced search form
	$("#adv_search_button").click(function() {
			var a_sz = $("#size").val();
			var a_st = $("#st").val();
			var a_pub = $("#public").val();
			var a_yrs = $("#years").val();
			
			$.post('lib/advancedSearch.php', { 
				size: a_sz,
				st: a_st,
				public: a_pub,
				years: a_yrs
			}, function(data) {
				if(data=="") {
					$('#adv_search_results').html("No results found.");
				} else {
					$('#adv_search_results').html(data);
				}
			});
										  
	});
	
	//submit dialog box
	$("#submit_dialog").dialog({
		bgiframe: true,
		autoOpen: false,
		modal: true,
		buttons: {
			Ok: function() {
				$(this).dialog('close');
			}
		}
	});
	
	
	//modal dialog form
	var fname = $("#fname"),
		lname = $("#lname"),
		add1 = $("#usr_add1"),
		add2 = $("#usr_add2"),
		city = $("#usr_city"),
		st = $("#usr_st"),
		zip = $("#usr_zip"),
		allFields = $([]).add(fname).add(lname).add(add1).add(add2).add(city).add(st).add(zip),
		tips = $("#validateTips");

	function updateTips(t) {
		tips.text(t).effect("highlight",{},1500);
	}

	function checkLength(o,n,min,max) {

		if ( o.val().length > max || o.val().length < min ) {
			o.addClass('ui-state-error');
			updateTips("Length of " + n + " must be between "+min+" and "+max+".");
			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;
		}

	}
	
	$("#dialog").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 600,
			width: 325,
			modal: true,
			closeOnEscape: true,
			buttons: {
				'Save My Info': function() {
					var bValid = true;
					allFields.removeClass('ui-state-error');

					bValid = bValid && checkLength(fname,"fname",3,26);
					bValid = bValid && checkLength(lname,"lname",3,26);
					bValid = bValid && checkLength(add1,"add1",3,46);
					bValid = bValid && checkLength(city,"city",1,46);
					bValid = bValid && checkLength(st,"st",2,3);
					bValid = bValid && checkLength(zip,"zip",5,5);

					//bValid = bValid && checkRegexp(fname,/^[a-z]([a-zA-Z])+$/i,"First Name may consist of a-z.");
					//bValid = bValid && checkRegexp(lname,/^[a-z]([a-zA-Z])+$/i,"Last Name may consist of a-z.");
					//bValid = bValid && checkRegexp(add1,/^[a-z]([a-zA-Z])+$/i,"Address may consist of 0-9, a-z.");
					//bValid = bValid && checkRegexp(city,/^[a-z]([a-zA-Z])+$/i,"Last Name may consist of a-z.");
					bValid = bValid && checkRegexp(st,/^[a-z]([a-zA-Z])+$/i,"State may consist of a-z.");
					bValid = bValid && checkRegexp(zip,/^[0-9]([0-9])+$/i,"Zip code may consist of digits 0-9.");
					
					
					
					if (bValid) {
						
						$.post("lib/saveinfocard.php", { 
							fnme: fname.val(),
							lnme: lname.val(),
							add: add1.val(),
							addtwo: add2.val(),
							cty: city.val(),
							ste: st.val(),
							zcode: zip.val()
						}, function (data) {
							//alert("Saved: " + data);
						});
						
						$(this).dialog('close');
					}
				}
			},
			close: function() {
				allFields.val('').removeClass('ui-state-error');
			}
		});
	
	
});

//auto complete functions
function adv_autoComplete(lastValue) {

	var part = $("#adv_search_field").val();
	
	// if it's empty clear the resuts box and return
	if(part == ''){
		clearAutoComplete();
		return;
	}

	// if it's equal the value from the time of the call, allow
	if(lastValue != part){
		return;
	}

	$.get('lib/searchColleges.php', { 
		val: lastValue
	}, function(data) {
		if(data=="") {
			$("#adv_target_bid").attr("value", "0");
			$("#adv_admisslist").hide();
		} else {
			$("#adv_admisslist").show();
			$('#adv_admisslist').html(data);
		}
	});

}

function clearAutoComplete() {
	$("#adv_admisslist").html('');
	$("#adv_admisslist").hide();
	$("#admisslist").html('');
	$("#admisslist").hide();
	
}

function adv_updownArrow(keyCode) {
	if(keyCode == 40 || keyCode == 38){
		var acListTotal = $("#adv_admisslist a").size();
		if(keyCode == 38){ // keyUp
			if(acListCurrent == 0 || acListCurrent == -1){
				acListCurrent = acListTotal-1;
			} else{
				acListCurrent--;
			}
		} else { // keyDown
			if(acListCurrent == acListTotal-1){
				acListCurrent = 0;
			} else {
				acListCurrent++;
			}
		}
		
		$("#adv_admisslist a").each(function(i){
			if(i == acListCurrent){
				$("#adv_search_field").val($(this).attr("sch"));
				
				offset = acListCurrent * 24;
				$("#adv_admisslist").scrollTop(offset);
			
				$(this).addClass("selected");
				var sbid = $(this).attr("bid");
				$("#adv_target_bid").attr("value", sbid);
			} else {
				$(this).removeClass("selected");
			}
		});
		
		return true;
	} else {
		// reset
		acListCurrent = -1;
		return false;
	}
}

function selectCollege(val, sbid) {
		$("input.sf").attr("value",val);
		$("input.sbid").attr("value", sbid);
		clearAutoComplete();
}

function sendmessage(boothID){
	mesg = document.getElementById("newmessage").value;
	if(mesg=="") {
		alert("You must enter a message before sending.");
		return;
	}
	//get recipients
	var recips = '';
	$("ul.rep_message_list li.selected").each(function(i) {
		recips += $(this).attr("rep") + ".";					   
	});
	//mesg = encodeURI(mesg);
	$.post("lib/newmessage.php", { 
			cid: boothID,
			msg: mesg,
			rcps: recips
		}, function (data) {
			document.getElementById("newmessage").value = "";
			$("#msg").slideUp(1000);
			$('ul.rep_message_list li').removeClass("selected");
			$("#msg_dialog").dialog('open');
		});
}

function vote(poll_id) {
	poll_choice = $(".pollclass" + poll_id + ":checked").val();
	$.post('http://www.virtualcollegefairs.com/booths/lib/voteonpoll.php', {
			vote: poll_choice,
			pid: poll_id
		}, function() {
			$("#pollspace"+poll_id).load('http://www.virtualcollegefairs.com/booths/lib/getPollResults.php?pid='+poll_id);
			$("#pollnum"+poll_id+ " input").hide("fast");
		});
}
function poll_results(poll_id){
	$("#pollspace"+poll_id).load('http://www.virtualcollegefairs.com/booths/lib/getPollResults.php?pid='+poll_id);
	$("#pollnum"+poll_id+ " input").hide("fast");
}

function websiteclick(clicktype, newurl) {
	if(newurl.substr(0,4)!="http") {
		newurl = "http://" + newurl;
	}
	window.open(newurl);
	$.get("http://www.virtualcollegefairs.com/booths/lib/recordWebClick.php", { 
			ctype: clicktype
		}, function () {
			
		});
}
function vtourclick(vid, newurl) {
	window.open("http://"+newurl);
	$.get("http://www.virtualcollegefairs.com/booths/lib/recordTourClick.php", { 
			visit:  vid
		}, function () {
			
		});
}
function recordSubmit() {
	$.get("http://www.virtualcollegefairs.com/booths/lib/recordSubmit.php", { 
			
		}, function () {
			$("#submit_dialog").dialog('open');
			$("#submit_button").attr("src", "images/submitted.png");
		});
}
function newdownload(path, docID, vid) {
	
	$.get("http://www.virtualcollegefairs.com/booths/lib/recordDownload.php", { 
			visit:  vid,
			doc: docID
		}, function () {
			window.open(path);
		});
}

function gettheRSS(idnum) {
	$("#blogfeed").load('http://www.virtualcollegefairs.com/booths/lib/getRSS.php?id='+idnum);
}

//ADD PIC
function ajaxPicUpload(college_id)
{
	
	document.getElementById("picholder").innerHTML = "";
	$("#picloading").show();

	$.ajaxFileUpload({
			url:'http://www.virtualcollegefairs.com/booths/lib/uploadcampuspic.php?cid='+college_id,
			secureuri:false,
			fileElementId:'picToUpload',
			dataType: 'json',
			success: function (data){
				$("#picloading").fadeOut(1000, function() {
					
					if(typeof(data.error) != 'undefined'){
						if(data.error != ''){
							alert(data.error);
						}else{
							document.getElementById("picholder").innerHTML = "<img src='http://www.virtualcollegefairs.com/Colleges/pics/tb_" + data.newfile + "'/><br/><input type='text' id='captiontxt' size='30'/><input type='hidden' id='newpicid' value='" + data.newid + "'/><br/><input type='button' value='Add Caption' onClick='saveCaption(1)'/><input type='button' value='No Caption' onClick='saveCaption(0)'/>";
							document.getElementById("picToUpload").value = "";
							var newpichtml = "<div class='imgspaceholder' id='img" + data.newid + "'><div class='imgholder'><a href='http://www.virtualcollegefairs.com/Colleges/pics/" + data.newfile + "' rel='prettyPhoto[gallery]' title=''><img src='http://www.virtualcollegefairs.com/Colleges/pics/tb_" + data.newfile + "' alt=''/></a></div><img src='/images/16px/star_off_16.png'/><img src='/images/16px/star_off_16.png'/><img src='/images/16px/star_off_16.png'/><img src='/images/16px/star_off_16.png'/></div>";
							$("#picture_gallery").append(newpichtml);
							$("#img" + data.newid).find("a").prettyPhoto();
							//$("a[rel^='prettyPhoto']").prettyPhoto();
						}
					}
				
				});
				
			},
			error: function (data, status, e){
				alert(e);
				$("#picloading").fadeOut(2000);
			}
		}
	)
	return false;
}

function saveCaption(y) {	

	if(y==0) {
		document.getElementById("picholder").innerHTML = "";
	} else {
		pnum = document.getElementById("newpicid").value;
		newcap = urlencode(document.getElementById("captiontxt").value);

		$.post('http://www.virtualcollegefairs.com/booths/lib/saveCaption.php', {
			cap: newcap,
			num: pnum
		}, function(data) {
			document.getElementById("picholder").innerHTML = "Caption saved.";
			$("#img" + pnum).find("a").attr("title", newcap); 
		});
	}
}

function urlencode(str) {                                
    var ret = str;
    ret = ret.toString();
	ret = ret.replace(/'/, "");
	ret = ret.replace(/"/, "");
    //ret = encodeURIComponent(ret); 
    return ret;
}

//post question
function askQuestion(bID) {
	var q = document.getElementById("questiontxt").value;
	if(q!="") {
		$.post('http://www.virtualcollegefairs.com/booths/lib/saveQuestion.php', {
			quest: q,
			board: bID
		}, function(data) {
			$("#faqlist").append(data);
			document.getElementById("questiontxt").value = "";
		});
	} else {
		alert("You must enter a question first.");
		 
	}
}


//START CHAT
function startchat(repid) {
	chatbox_id = randomChatBoxID(10);
	chatboxes[chatbox] = window.open('', 'open_window'+chatbox_id,'menubar=no, toolbar=no, location=no, directories=no, status=no, scrollbars=no, resizable=no, dependent, width=338, height=620, left=0, top=0');
	chatbox = chatbox + 1;
	$.post('http://www.virtualcollegefairs.com/booths/lib/startchat.php', {
			rep: repid
		}, function(data) {
			cid = data;
			chatboxes[chatbox-1].document.location = 'http://www.virtualcollegefairs.com/ChatObject/cb_visitorchat.php?cid='+cid;
		});
//	window.open('chatwindow.php?rep='+repid, 'open_window'+chatbox_id,'menubar=no, toolbar=no, location=no, directories=no, status=no, scrollbars=no, resizable=no, dependent, width=338, height=620, left=0, top=0');
}


function facebook_onlogin() {
	document.location = "http://www.virtualcollegefairs.com/fb_login.php5";
}


//WAVE FUNCTIONS

var positions = new Array();

function addComment(where,parent,u_r_l){
	var $el;
	if($('.waveButton').length) return false;

	if(!where)
		$el = $('#' + u_r_l);
	else
		$el = $(where).closest('.waveComment');

	if(!parent) parent=0;

	if(u_r_l=="saveComment")
		button_label = "Add a comment";
	else
		button_label = "Ask a question";

	$('.waveComment').show('slow');

	var comment = '<div class="waveComment addComment">\
	\
	<div class="comment">\
	<div class="commentAvatar">\
	<img src="images/demo.png" width="30" height="30" />\
	</div>\
	\
	<div class="commentText">\
	\
	<textarea class="textArea" rows="2" name="" />\
	<div><input type="button" class="waveButton" value="'+button_label+'" onclick="addSubmit(this,'+parent+',\''+u_r_l+'\')" /> or <a href="" onclick="cancelAdd(this);return false">cancel</a></div>\
	\
	</div>\
	</div>\
	\
	</div>';

	$el.append(comment);
}

function cancelAdd(el){
	$(el).closest('.waveComment').remove();
}

function addSubmit(el,parent,u_r_l){
	var cText = $(el).closest('.commentText');
	var text = cText.find('textarea').val();
	var wC = $(el).closest('.waveComment');
	if(text.length<4){
		alert("Your comment is too short!");
		return false;
	}

	$(el).parent().html('<img src="images/ajax_load.gif" width="16" height="16" />');
	
	$.ajax({
		type: "POST",
		url: "lib/" + u_r_l + ".php",
		data: "comment="+encodeURIComponent(text)+"&parent="+parent,
		success: function(msg){
			var ins_id = parseInt(msg);
			if(ins_id){
				wC.addClass('com-'+ins_id);
			}
			transForm(text,cText);
		}
	});
}

function transForm(text,cText){
	var tmpStr ='<span class="name">You:</span> '+text;
	cText.html(tmpStr);
}