$(document).ready(function() { /*jQuery DOM ready */
	
	/* prepare footer tech-links */
	$("#footer #tech-links ul li").hover(function() {
		$(this).css("background-position","left bottom");
	}, function() {
		$(this).css("background-position","left top");
	});
	
	/* init hover listeners */
	init_hovers();
	
	/* login click listener */
	$("#submit").click(function() {
		$("#submit").css({"background-position":"bottom left"});
	}, function() {
		$("#submit").css({"background-position":"top left"});
	})
	
	/* header trigger listener */
	$("#header_trigger").click(function() {
		window.location = "index.php";
	})
	
	/* nav hash change listener */
	$("#nav").delegate("a", "click", function() {
		var $curr_hash = window.location.hash.substring(1);
		if($(this).attr("href") != $curr_hash) {
			window.location.hash = $(this).attr("href");
			$(this).blur();
		}
		return false;
	});
	$("#footer a#contact").click(function() {
		window.location.hash = $(this).attr("href");
		$(this).blur();
		return false;
	});
	
	/* nav function */ 
	$(window).bind('hashchange',function() {
		target_hash = window.location.hash.substring(1);
		if(target_hash) { // if there is a hash...
			// clear nav indicators and set new active...
			$("#nav li.active").removeClass("active");
			var $target_page = target_hash.substring(0,target_hash.indexOf('.php'));
			$("#nav li#"+$target_page).addClass("active");
			//load target page contents into framework...
			$("#page").find("#xfer").fadeOut(100, function() {
				$("#page").hide().load(target_hash + " #xfer", function() { 
					$("#page").fadeIn(300);
					$('.col').equalizeBottoms();
					
					$(document).ready(function() {
						init_hovers();
						$("#content a").tooltip({tip:'#tooltip',effect: 'slide', slideOffset: 5});
						// set head title to match pagetitle element...
						$("title").text($("#pagetitle").text());
					});
					// specific page logic ...
					if($target_page == 'articles') {
						get_content(target_hash);
					}
					if($target_page == 'contact') {
						choice('contact_route','designs');
					}
				})
			});
		} else {
			loc = window.location.href;
			//console.log("loc="+loc);
			pg = loc.substring(loc.indexOf('swinginsam.com')+15,loc.indexOf('.php'));
			//console.log("pg="+pg);
			if(pg == window.location.href) {
				//console.log("no hash detected. setting page to index");
				tar = "#index.php";
			} else if(pg == 'articles') {
				//console.log("articles detected. reading req id");
				req = loc.substring(loc.indexOf('?req=')+5,9999);
				if(req == loc.substring(4,9999)) {
					//console.log("no req id found. setting to 1");
					req = 1;
				}
				tar = "index.php#articles.php?req="+req;
			} else {
				//console.log("hash detected. setting index and hash");
				tar = "index.php#"+pg+".php";
			}
			//console.log("sequence complete... pg = "+tar);
			window.location.href = tar;
			$("#nav li#"+pg).addClass("active"); // if there is no hash, then indicate the index page
		}
	});
	
	// initial navigation trigger
	$(window).trigger('hashchange');
	
});

/* AJAX FRAMEWORK */
var xmlHttp;
function GetXmlHttpObject() { 
	var objXMLHttp=null;
	if (window.XMLHttpRequest) {
		objXMLHttp=new XMLHttpRequest()
	} else if (window.ActiveXObject) {
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	return objXMLHttp;
}

function format_code(id) {
	console.log('code init for id' + id);
	if(document.getElementById(id)) {
		var replText = document.getElementById(id).innerHTML.replace(new RegExp( "\\n", "g" ),"\n<span class=\"line_num\">...</span>");
		document.getElementById(id).innerHTML = "<span class=\"line_num\">...</span>"+replText;
		var replText = document.getElementById(id).innerHTML.replace(new RegExp( "\\t", "g" ),"  ");
		document.getElementById(id).innerHTML = replText;
		var ln = 1;
		$('pre span.line_num').each(function() {
			$(this).replaceWith('<span class=\"line_num\">'+ln+'</span>');
			ln++;
		});
	}
}

function init_hovers() {
	$("#works li").hover(function() {
		$(this).addClass("glow");
	}, function() {
		$(this).addClass("trans");
		$(this).removeClass("glow");
	});
	$("#nav li:not('.active')").hover(function() {
		$(this).find(" div.nav_label").show().animate( {"opacity":"1.0"} );
		$(this).find(" a").addClass("indicate");
	}, function() {
		$(this).find(" div.nav_label").animate( {"opacity":"0"} ).hide();
		$(this).find(" a").removeClass("indicate");
	});
	$("#footer a").hover(function() {
		$(this).find(" div.footer_label").show().animate( {"opacity":"1.0"} );
	}, function() {
		$(this).find(" div.footer_label").animate( {"opacity":"0" } ).hide();
	});
	$("#portal").hover(function() {
		$(this).find(" div.portal_label").show().animate( {"opacity":"1.0"} );
	}, function() {
		$(this).find(" div.portal_label").animate( {"opacity":"0" } ).hide();
	});
	$("#colourbox_player").hover(function() {
		$(this).find(" div.colourbox_label").show().animate( {"opacity":"1.0"} );
	}, function() {
		$(this).find(" div.colourbox_label").animate( {"opacity":"0"} ).hide();
	});
	$("#portfolio_player").hover(function() {
		$(this).find(" div.portfolio_label").show().animate( {"opacity":"1.0"} );
	}, function() {
		$(this).find(" div.portfolio_label").animate( {"opacity":"0"} ).hide();
	});
}

function get_content(target_hash) {
	var $id = target_hash.substring(target_hash.indexOf('req=')+4,9999);
	//console.log("$id = "+$id);
	if(!isNull($id)&&$id !='icles.php') {
		$("#load").fadeIn(50);
		$("#content").fadeOut(100, function() {															 	
			$("#main").load("_data/articles_content.php #content_"+$id, function() {
				$("#title_content").fadeOut(100, function() {
					$("#article_title").load("_data/articles_content.php #title_content_"+$id);
				});
				$("#content").fadeIn(100);
				$("#title_content").fadeIn(100);
				$("#load").fadeOut(100);
				$(function(){
					$('.col').equalizeBottoms();
					$("#main a").tooltip({tip:'#tooltip',effect: 'slide', slideOffset: 5});
				});
			});
		});
	}
}

function verify_auth() {
	$("#load").fadeIn(50);
	var key = document.getElementById('auth_key').value;
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {
		alert ("Browser does not support HTTP Request");
		return;
	}
	var url="_scripts/ssd_ajax.php";
	url=url+"?FTC=verify_auth";
	url=url+"&key="+key;
	url=url+"&sid="+Math.random();
	xmlHttp.onreadystatechange=response_verify_auth;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	return false;
}

function response_verify_auth() {
	if(xmlHttp.responseText != '0') {
		if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
			$("#page").find("#xfer").fadeOut(100, function() {
				$("#page").hide(function() { 
					document.getElementById('xfer').innerHTML = xmlHttp.responseText;
					document.getElementById('auth_key').value = "";
					document.getElementById('auth_key').blur();
					$("#xfer").show();
					$("#page").fadeIn(300);
				})
			});
		}
		$("#load").fadeOut(100);
	}
}

function choice(obj,val) {
	switch(obj) {
		case 'contact_route' : {
			var fields_ary = new Array('telephone','company','change_type','urgency','url','multi','alt_url','current_content','new_content','os','browser','description');
			/* hide all non-universal fields */
			$("#load").fadeIn(50);
			document.getElementById('contact_multi').checked = false;
			document.getElementById('contact_change_type_0').checked=true;
			document.getElementById('contact_change_type_1').checked=false;
			for(kk=0;kk<=(fields_ary.length)-1;kk++) {
				$("#contact_form #div_contact_"+fields_ary[kk]).hide();	
			}
			/* then display the necessary fields for the contact type selected */
			if(val == 'designs') {
				$("#contact_form #div_contact_telephone").show(200,function() {
					$("#contact_form #div_contact_company").show(200,function() {
						$("#load").fadeOut(100);
					});
				});
			} else if(val == 'clients') {
				$("#contact_form #div_contact_change_type").show(200,function() {
					$("#contact_form #div_contact_urgency").show(200,function() {
						$("#contact_form #div_contact_url").show(200,function() {																												
							$("#contact_form #div_contact_multi").show(200,function() {
								$("#contact_form #div_contact_current_content").show(200,function() {
									$("#contact_form #div_contact_new_content").show(200,function() {
										$("#load").fadeOut(100);
									});
								});
							});
						});
					});
				});
			} else if(val == 'bugs') {
				$("#contact_form #div_contact_url").show(200,function() {
					$("#contact_form #div_contact_os").show(200,function() {
						$("#contact_form #div_contact_browser").show(200,function() {
							$("#contact_form #div_contact_description").show(200,function() {
								$("#load").fadeOut(100);
							});						
						});
					});
				});
			}
			break;
		}
		case 'contact_multi' : {
			if(val) {
				$("#contact_form #div_contact_alt_url").show(200);
			} else {
				$("#contact_form #div_contact_alt_url").hide(200);
			}
			break;
		}
		case 'contact_change_type' : {
			if(val=='new') {
				$("#contact_form #div_contact_current_content").hide(200);
			} else if(val=='existing') {
				$("#contact_form #div_contact_current_content").show(200);
			}
			break;
		}
		default : {}
	}
}

function validate_contact() {
	$("#contact_stage").val(1);
	clear_fb();
	var $box = $("#contact_route");
	var $fn = $("#contact_firstname");
	var $ln = $("#contact_lastname");
	var $email = $("#contact_email");
	var $telephone = $("#contact_telephone");
	var $company = $("#contact_company");
	var $change_type = $("#contact_change_type_0");
	var $urgency = $("#contact_urgency");
	var $url = $("#contact_url");
	var $multi = $("#contact_multi");
	var $alt_url = $("#contact_alt_url");
	var $current_content = $("#contact_current_content");
	var $new_content = $("#contact_new_content");
	var $os = $("#contact_os");
	var $browser = $("#contact_browser");
	var $description = $("#contact_description");
	var $comment = $("#contact_comment");
	
	// first, get the ones common to all route types...
	if(isBlank($fn.val()) || !(isAlpha($fn.val()))) {
		$("#fb_contact_firstname").text("Please enter your first name.");
		$fn.focus();
		return false;
	}
	if(isBlank($ln.val()) || !(isAlpha($ln.val()))) {
		$("#fb_contact_lastname").text("Please enter your last name.");
		$ln.focus();
		return false;
	}
	if(isBlank($email.val()) || !(isValidEmail($email.val()))) {
		$("#fb_contact_email").text("Please enter a valid email address.");
		$email.focus();
		return false;
	}
	
	//next get the one specific to the route selection
	switch($box.val()) {
		case 'designs' : {
			//required fields :: firstname, lastname, email, comment
			if(isBlank($comment.val())) {
				$("#fb_contact_comment").text("Please enter a message.");
				$comment.focus();
				return false;
			}
			break;
		}
		case 'clients' : {
			//required fields :: firstname, lastname, email, url, **alt_arl**, **current_content**, new_content
			if(isBlank($url.val())) {
				$("#fb_contact_url").text("Please enter the URL of the page in question");
				$url.focus();
				return false;
			}
			if($multi.is(':checked')) {
				if(isBlank($alt_url.val())) {
					$("#fb_contact_alt_url").text("Please enter the URL for each additional page you need changed.");
					$alt_url.focus();
					return false;
				}
			}
			if($change_type.is(':checked')) {
				if(isBlank($current_content.val())) {
					$("#fb_contact_current_content").text("Please paste the current content into the text area.");
					$current_content.focus();
					return false;
				}
			}
			if(isBlank($new_content.val())) {
				$("#fb_contact_new_content").text("Please enter your new content into the text area.");
				$new_content.focus();
				return false;
			}
			break;
		}
		case 'bugs' : {
			//required fields :: firstname, lastname, email, url, os, browser, description
			if(isBlank($url.val())) {
				$("#fb_contact_url").text("Please enter the URL of the page in question");
				$url.focus();
				return false;
			}
			if(isBlank($os.val())) {
				$("#fb_contact_os").text("Please select the OS you were using when you experienced this problem.");
				$os.focus();
				return false;
			}
			if(isBlank($browser.val())) {
				$("#fb_contact_browser").text("Please select the browser you were using when you experienced this problem.");
				$browser.focus();
				return false;
			}
			if(isBlank($description.val())) {
				$("#fb_contact_description").text("Please enter a detailed description of the problem you experienced.");
				$description.focus();
				return false;
			}
			break;
		}
		default : {}
	}
	if(confirm("Ready to Submit? \n\nClick 'OK' to send your request or 'CANCEL' to go back and make changes.")) {
		send_contact($box.val());
	}
	return false;
}

function clear_fb() {
	$("#contact_form").find(" span.fb").text("");
}

function isUndef(val) {
	isValid = false;
	if(val+"" == void(0)) { isValid = true; }
	return isValid;
}

function isNull(val) {
	isValid = false;
	if(val+"" == "null") { isValid = true; }
	return isValid;
}

function isBlank(str) {
	isValid = false;
	if(isNull(str) || isUndef(str) || (str+"" == "")) { isValid = true; }
	return isValid;
}

function isValidEmail(str) {
	 var isValid = true;
   str += "";
   namestr = str.substring(0, str.indexOf("@"));              // everything before the '@'
   domainstr = str.substring(str.indexOf("@")+1, str.length); // everything after the '@'
   // Rules: namestr cannot be empty, or that would indicate no characters before the '@', domainstr must contain a period that is not the first character (i.e. right after the '@').  The last character must be an alpha.
   if ((namestr.length == 0) || (domainstr.indexOf(".") <= 0)  || (str.indexOf("'") != -1) || (str.indexOf("@") == -1) || (domainstr.indexOf("@") != -1) || (!isAlpha(str.charAt(str.length-1)))) {
     isValid = false;
   }
   return isValid;
}

function isAlpha(str) {
	if(str+"" == void(0) || str+"" == "null" || str+"" == "") { return false; }
	var isValid = true;
	// convert to a string for performing string comparisons.
	str += "";
	for (i=0; i<str.length; i++) {
		if(!(((str.charAt(i) >= "a") && (str.charAt(i) <= "z")) || ((str.charAt(i) >= "A") && (str.charAt(i) <= "Z")) || ((str.charAt(i) == "-")))) {
			isValid = false;
			break;
		}
	}
	return isValid;
}

function isInt(numstr, allowNegatives) {
	if(numstr+"" == void(0) || numstr+"" == "null" || numstr+"" == "") { return false; }
	// Default allowNegatives to true when undefined or null
	if (allowNegatives+"" == void(0) || allowNegatives+"" == "null") { allowNegatives = true; }
	var isValid = true;
	// convert to a string for performing string comparisons.
	numstr += "";
	for(i=0; i<numstr.length; i++) {
		if(!((numstr.charAt(i) >= "0") && (numstr.charAt(i) <= "9") || (numstr.charAt(i) == "-"))) {
			isValid = false;
			break;
		} else {
			if((numstr.charAt(i) == "-" && i != 0) || (numstr.charAt(i) == "-" && !allowNegatives)) {
				isValid = false;
				break;
			}
		}
	}
	return isValid;
}

function IsNum(numst) {
	// Return immediately if an invalid value was passed in
	if(numstr+"" == void(0) || numstr+"" == "null" || numstr+"" == "") { return false; }
	var isValid = true;
	var decCount = 0; // number of decimal points in the string
	// convert to a string for performing string comparisons.
	numstr += "";
	// Loop through string and test each character. If any character is not a number, return a false result.
	// Include special cases for negative numbers (first char == '-') and a single decimal point (any one char in string == '.').
	for (i=0; i<numstr.length; i++) {
		if(numstr.charAt(i) == ".") { decCount++; }
		if(!((numstr.charAt(i) >= "0") && (numstr.charAt(i) <= "9") || (numstr.charAt(i) == "-") || (numstr.charAt(i) == "."))) {
			isValid = false;
			break;
		} else {
			if ((numstr.charAt(i) == "-" && i != 0) ||
					(numstr.charAt(i) == "." && numstr.length == 1) ||
					(numstr.charAt(i) == "." && decCount > 1)) {
				isValid = false;
				break;
			}
		}
	}
	return isValid;
}

function send_contact(type) {
	$("#load").fadeIn(50);
	var $box = $("#contact_route").val();
	var $fn = $("#contact_firstname").val();
	var $ln = $("#contact_lastname").val();
	var $email = $("#contact_email").val();
	var $telephone = $("#contact_telephone").val();
	var $company = $("#contact_company").val();
	var $change_type = $("#contact_change_type_0").val();
	var $urgency = $("#contact_urgency").val();
	var $url = $("#contact_url").val();
	var $multi = $("#contact_multi").val();
	var $alt_url = $("#contact_alt_url").val();
	var $current_content = $("#contact_current_content").val();
	var $new_content = $("#contact_new_content").val();
	var $os = $("#contact_os").val();
	var $browser = $("#contact_browser").val();
	var $description = $("#contact_description").val();
	var $comment = $("#contact_comment").val();
	
	$ajax_data = "FTC=send_contact";
	$ajax_data += "&box="+$box;
	$ajax_data += "&fn="+$fn;
	$ajax_data += "&ln="+$ln;
	$ajax_data += "&em="+$email;
	$ajax_data += "&tel="+$telephone;
	$ajax_data += "&co="+$company;
	$ajax_data += "&chng="+$change_type;
	$ajax_data += "&urgcy="+$urgency;
	$ajax_data += "&url="+$url;
	$ajax_data += "&multi="+$multi;
	$ajax_data += "&alturl="+$alt_url;
	$ajax_data += "&c_content="+$current_content;
	$ajax_data += "&n_content="+$new_content;
	$ajax_data += "&os="+$os;
	$ajax_data += "&br="+$browser;
	$ajax_data += "&desc="+$description;
	$ajax_data += "&cmt="+$comment;
	
	
	$.ajax({
		url: "_scripts/ssd_ajax.php",
		type: "POST",
		data: $ajax_data,
		dataType: "html",
		success: function(msg){
			 if(msg == "pass") {
					$("#contact_form").hide(100,function() {
						$("#pass").show(500);
					})
			 } else if(msg == "fail") {
				 $("#contact_form").hide(100,function() {
						$("#fail").show(500);
					})
			 } else {
				 alert(msg);
			 }
			 $("#load").fadeOut(100);
		}
	});
}

/* TEMPORARY SCRIPTS - ARTICLES */

function change_colour(rgb) {
	$("#colour_box").css({"background":rgb});
}