// JavaScript Document
//Purpose: Site scripts
//Created: 8/04/11 by Martin Franklin

// addthis config 
var addthis_config = {"data_track_clickback":true};
// Bing config
var AppId = "F136BE16D32257AA91A8A359EB17F9EF0A70787A";
// Bing site filter
var siteFilter = "";

// loads any scripts before page display using jQuery ready fn
load_scripts = function(){
	// bing search load 
		$('#bingsearch').submit(function(e) {
    	// prevent default submit behavior
		e.preventDefault();
		// sumbit query to bing
		searchBing();
	})
}

// form validator
validate_ContactForm = function(){
	$.validator.setDefaults({
		submitHandler: function() { alert("Thank your for your inquiry, someone will contact you shortly!"); }
	});
	
	// validate signup form on keyup and submit
	$("#contactform").validate({
		rules: {
			name: "required",
			email: {
				required: true,
				email: true
			},
			phone: "required" ,
			comment: {
				required:true,
				minlength:5
			}
		},
		messages: {
			name: "* Please enter your name",
			email: "* Please enter a valid email address",
			phone: "* Please provide a phone number",
			comment: "* Please provide a comment"
		}
	});
}

// Bing API 2.0 code
// Web SourceType over the JSON Protocol.
searchBing = function()
		{
		var search_input = encodeURIComponent($.trim($('#searchTerm').val()));
		var qString = siteFilter + search_input;
		var requestStr = "http://api.bing.net/json.aspx?"
		//console.log(lang);
		// Common request fields (required)
		+ "AppId=" + AppId
		+ "&Query=" + qString
		+ "&Sources=Web"
		// Common request fields (optional)
		+ "&Version=2.0"
		+ "&Market=en-us"
		+ "&Adult=Strict"
		+ "&Options=EnableHighlighting"
		// Web-specific request fields (optional)
		+ "&Web.Count=10"
		+ "&Web.Offset=0"
		+ "&Web.Options=DisableHostCollapsing+DisableQueryAlterations"
		// JSON-specific request fields (optional)
		+ "&JsonType=callback"
		+ "&JsonCallback=SearchCompleted";
		var script = document.createElement('script');
		script.src = requestStr;
		script.type = 'text/javascript';
		var head = document.getElementsByTagName('head').item(0);
		head.appendChild(script);
		}
		function SearchCompleted(response)
		{
		var errors = response.SearchResponse.Errors;
		if (errors != null)
		{
		// There are errors in the response. Display error details.
		DisplayErrors(errors);
		}
		else
		{
		// There were no errors in the response. Display the
		// Web results.
		$('#bingoutput').html('');
		DisplayResults(response);
		}
		}
		function DisplayResults(response)
		{
		var output = document.getElementById("bingoutput");
		var resultsHeader = document.createElement("h4");
		var resultsList = document.createElement("ul");
		output.appendChild(resultsHeader);
		output.appendChild(resultsList);
		if(response.SearchResponse.Web.Results != undefined){
		var results = response.SearchResponse.Web.Results;
		// Display the results header.
		resultsHeader.innerHTML = "<a href='#' id='searchExit'></a>"
		+ "<br />Displaying "
		+ (response.SearchResponse.Web.Offset + 1)
		+ " to "
		+ (response.SearchResponse.Web.Offset + results.length)
		+ " of "
		+ response.SearchResponse.Web.Total
		+ " results<br />";
		// Display the Web results.
		var resultsListItem = null;
		var resultStr = "";
		for (var i = 0; i < results.length; ++i)
		{
		resultsListItem = document.createElement("li");
		resultsList.appendChild(resultsListItem);
		resultStr = "<a href=\""
		+ results[i].Url
		+ "\">"
		+ results[i].Title
		+ "</a><br />"
		+ results[i].Description
		+ "<br /><span class='resultDetails'>Last Crawled: "
		+ results[i].DateTime+"</span>"
		+ "<br /><br />";
		// Replace highlighting characters with strong tags.
		resultsListItem.innerHTML = ReplaceHighlightingCharacters(
		resultStr,
		"<strong>",
		"</strong>");
		}
		$('#searchExit').click(function(){
		$('#bingoutput').hide();
		});
		$('#bingoutput').show();
		}else{
		$('#searchTerm').val('No Results...');
		$('#bingoutput').hide();
		}
		}
		function ReplaceHighlightingCharacters(text, beginStr, endStr)
		{
		// Replace all occurrences of U+E000 (begin highlighting) with
		// beginStr. Replace all occurrences of U+E001 (end highlighting)
		// with endStr.
		var regexBegin = new RegExp("\uE000", "g");
		var regexEnd = new RegExp("\uE001", "g");
		return text.replace(regexBegin, beginStr).replace(regexEnd, endStr);
		}
		function DisplayErrors(errors)
		{
		var output = document.getElementById("output");
		var errorsHeader = document.createElement("h4");
		var errorsList = document.createElement("ul");
		output.appendChild(errorsHeader);
		output.appendChild(errorsList);
		// Iterate over the list of errors and display error details.
		errorsHeader.innerHTML = "Errors:";
		var errorsListItem = null;
		for (var i = 0; i < errors.length; ++i)
		{
		errorsListItem = document.createElement("li");
		errorsList.appendChild(errorsListItem);
		errorsListItem.innerHTML = "";
		for (var errorDetail in errors[i])
		{
		errorsListItem.innerHTML += errorDetail
		+ ": "
		+ errors[i][errorDetail]
		+ "<br />";
		}
		errorsListItem.innerHTML += "<br />";
		}
}

// Gizmo Control START 
// param 1 define div's for gizmo and be sure to float content right or left
var targetIds = new Array('sImage1', 'sImage2', 'sImage3', 'sImage4');
// gizmo div start sz
var startWidth = "120px";
// gizmo expanded sz
var maxWidth = "210px";
		
		gizmo_load = function(){
			// attach evt handler to each div as specified in targetIds array
			$.each(targetIds, function(index, value){
					$('#'+value).bind('click', function(){expand_Id(this.id);					
				});
			});
					
		}
			
		// expand target and contract others
		expand_Id = function(currId){
			var currEl;
			$.each(targetIds, function(index, value){				
				currEl = $('#'+value);
				
				if(value==currId && $(currEl).attr('class') != 'on'){
					$(currEl).animate({
									width : maxWidth,
									}, 1500, function(){
										 	$('#'+this.id).addClass('on');
										 });	
					
									$("#gizmoInner").animate({
											width : 580,
															 }, 1500 );
										
				}else{
					$(currEl).animate({
									width : startWidth,
									}, 1500).removeClass('on');	
														
				}
			
			});
		}
// Gizmo control END

/*
 * MovingBoxes demo script
 */

runBoxSlider = function(){

	$('#box-slider').movingBoxes({
		startPanel   : 3,      // start with this panel
		width        : 650,    // overall width of movingBoxes (not including navigation arrows)
		panelWidth   : .7,     // current panel width adjusted to 70% of overall width
		buildNav     : false,   // if true, navigation links will be added
		navFormatter : function(index, panel){ return panel.find('h2 span').text(); } // function which gets nav text from span inside the panel header
	});


	// Report events to firebug console
/*	$('.mb-slider').bind('initialized.movingBoxes initChange.movingBoxes beforeAnimation.movingBoxes completed.movingBoxes',function(e, slider, tar){
		// show object ID + event in the firebug console
		// namespaced events: e.g. e.type = "completed", e.namespace = "movingBoxes"
		if (window.console && window.console.firebug){
			var txt = slider.$el[0].id + ': ' + e.type + ', now on panel #' + slider.curPanel + ', targeted panel is ' + tar;
			console.debug( txt );
		}
	});
*/
}

/*
 * MovingBoxes END
 */
