//
// GSS Functions
//

//
//	Load any global variables here
//
var sid = getCookie("LOGIN_COOKIE");
var AdServer = {};

//
//	Main GSS Functions
//
function AdServer_rotateAd(elm) {

	//return setTimeout(function() {AdServer_getAd(elm)}, 3);

}

function Timer(callback, delay) {
	var timerId, start, remaining = delay;

	this.pause = function() {
		window.clearTimeout(timerId);
		remaining -= new Date() - start;
	};

	this.resume = function() {
		start = new Date();
		timerId = window.setTimeout(callback, remaining);
	};

	this.resume();
}


function AdServer_getAd(elm, adspot) {
	elm = $(elm);

	//	Only bind the hover event on the first call to getAd()
	if( !AdServer.timeoutSet ) {
		AdServer.timeoutSet = 1;

		//	Set hover over action
		$(elm).hover( function() {
			AdServer.timeout.pause();
		}, function() {
			//	re set timeout
			AdServer.timeout.resume();
		});
	}

	//	Now retrieve an ad for this spot and setup rotate duration using the Timer object
	jsonGSS("AdServer", {
			func: "getAd",
			adspot_id: adspot
		},
		function(data) {
			//	Logging Complete
			elm.attr('href', data.destination_url );
			$('img', elm).attr('name', data.id );
			elm.find('img').attr('src', data.src );
			AdServer_outbound(elm, data.group_id);
			//	Require a minimum of 3 second banner displays
			if( data.duration < 3 ) {
				data.duration = 3;
			}

			AdServer.timeout = new Timer( function() {AdServer_getAd(elm, adspot)}, data.duration);
		});

}

function AdServer_outbound( elm, group_id ) {
	$(elm).unbind('click');
	$(elm).click(
		function(event) {

			event.preventDefault();

			apiGSS("AdServer", {
					func:	"logHit",
					b_id:	event.target.name,
					g_id:	group_id
				},
				function(urlData) {
					//	Logging Complete
					window.location = $(elm).attr('href');
				});

		});
}

function strip_tags(html){
 
		//PROCESS STRING
		if(arguments.length < 3) {
			html=html.replace(/<\/?(?!\!)[^>]*>/gi, '');
		} else {
			var allowed = arguments[1];
			var specified = eval("["+arguments[2]+"]");
			if(allowed){
				var regex='</?(?!(' + specified.join('|') + '))\b[^>]*>';
				html=html.replace(new RegExp(regex, 'gi'), '');
			} else{
				var regex='</?(' + specified.join('|') + ')\b[^>]*>';
				html=html.replace(new RegExp(regex, 'gi'), '');
			}
		}
 
		//CHANGE NAME TO CLEAN JUST BECAUSE 
		var clean_string = html;
 
		//RETURN THE CLEAN STRING
		return clean_string;
	}

function parseBreadcrumbsForTitle( link ) {
    var pieces = strip_tags(link).split( "|" );
    var newTitle = '';
    for( i=pieces.length-1; i>=0; i-- ) {
       //alert( pieces[i] );
       newTitle += pieces[i] + " | ";
    }
    return newTitle;
}

function apiGSS( action, params, callback ) {
	serverApi = "/GSS.php";
	params['action'] = action;
	params['sid'] = sid;
	params['cache'] = false;
	$.get( serverApi,
		params,
		callback
	);
}

function jsonGSS( action, params, callback ) {
	serverApi = "/GSS.php";
	params['action'] = action;
	var sid = getCookie("LOGIN_COOKIE");
	params['sid'] = sid;
	params['cache'] = false;
	$.getJSON( serverApi,
		params,
		callback
	);
	
	/*
	if( !params['dataType'] ) {
		params['dataType'] = 'json';
	}
	apiGSS(action, params, callback);
	*/
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/*	Some template and html working functions */

// Clear all inputs in jQuery element
function formClearInputs(elm) {
	$("input[type=text]", elm).val('');
}

function strpos (haystack, needle, offset) {
	// Finds position of first occurrence of a string within another  
	// 
	// version: 1103.1210
	// discuss at: http://phpjs.org/functions/strpos    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: Onno Marsman    
	// +   bugfixed by: Daniel Esteban
	// +   improved by: Brett Zamir (http://brett-zamir.me)
	// *     example 1: strpos('Kevin van Zonneveld', 'e', 5);    // *     returns 1: 14
	var i = (haystack + '').toLowerCase().indexOf(needle.toLowerCase(), (offset || 0));
	return i === -1 ? false : i;
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function isNumber(n) {
	return !isNaN(parseFloat(n)) && isFinite(n);
}

/*
	Template( rawTemplate, data )

		Setup a template style object to handle rendering data to html in a template div
			templateRender looks for strings in rawTemplate with keys from the data object that enclosed in brackets like this "{key}" and replaces it with the objects value for that key.

		Input:
			rawTemplate is a string of html
			data is a JSON object
		Returns:
			Template object

	Example Usage:

		var tplLine = new Template( "#idElement" );
		tplLine.data( dataObject );
		$("#destination").append( tplLine.render() );

	Methods:
		data( dataObject )
			Assign the object the data to use for rendering

			Input:
				dataObject is the data object to be used for rendering
			Returns:
				current data object

		render( dataObject )
			Render the data object to the template

			Input:
				dataObject is the option data object to be used
			Returns:
				html string

		hide()
			Hides the original template object

*/
function Template(elm, data) {
	
	//	Init this object
	this.origElm = elm;
	this.elm = $(elm).clone().html();
	this.elm = decodeURI(this.elm);

	//	Setup functions
	this.data = function(data) {
		if( data ) {
			this.data = data;
		}
		return this.data;
	};
	this.render = function(data) {
		if( data ) {
			this.data = data;
		}
		return templateRender( this.elm, this.data );
	};
	this.hide = function() {
		$(this.origElm).hide();
	};

	//	Post setup behaviour

	//	Default behaviour to hide original template
	this.hide();

	//	Assign data if defined
	if( data ) {
		this.data(data);
	}

}

function templateRender( rawTemplate, data ) {
	jQuery.each( data, function(key, value) {
		var match = new RegExp( "{"+key+"}", "ig");
		rawTemplate = rawTemplate.replace( match, value );
		});
	return rawTemplate;
}
