// A few variables
var busy = "<div id='busy' class='ui-widget busy'><div class='ui-state-highlight ui-corner-all' style='margin-top: 20px; padding: 0 .7em;'><p><span class='ui-icon ui-icon-clock' style='float: left; margin-right: .3em;'></span><strong>Busy:</strong> <span id='result'>Sending the request ...</span></p></div><br></div>"



// DETECTS BROWSER VERSION //
/* not in use at the moment */
var browser = function()
{
	var browserDetect = {
		init: function () {
			this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
			this.OS = this.searchString(this.dataOS) || "an unknown OS";
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1)
						return data[i].identity;
				}
				else if (dataProp)
					return data[i].identity;
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		dataBrowser:
				[
			{string: navigator.userAgent, subString: "Chrome", identity: "Chrome"},
			{string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb"},
			{string: navigator.vendor, subString: "Apple", identity: "Safari", versionSearch: "Version"},
			{prop: window.opera, identity: "Opera"},
			{string: navigator.vendor, subString: "iCab", identity: "iCab"},
			{string: navigator.vendor, subString: "KDE", identity: "Konqueror"},
			{string: navigator.userAgent, subString: "Firefox", identity: "Firefox"},
			{string: navigator.vendor, subString: "Camino", identity: "Camino"},
			{string: navigator.userAgent, subString: "Netscape", identity: "Netscape"},
			{string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE"},
			{string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv"},
			{string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla"}
				],
		dataOS : 
				[
			{string: navigator.platform, subString: "Win", identity: "Windows"},
			{string: navigator.platform, subString: "Mac", identity: "Mac"},
			{string: navigator.userAgent, subString: "iPhone", identity: "iPhone/iPod"},
			{string: navigator.platform, subString: "Linux", identity: "Linux"}
				]
	};
	browserDetect.init();
	return browserDetect.browser
}




// AJAX CALLS //
var ajaxify = function(){
	$('.ajaxPOST').each(function(i, e){
		$(e).submit(function(){
						
			// Set this form to busy
			$(e).children(".result").html(busy);
			
			// Show Data for this form
			$(e).children(".result").show();
			
			$.ajax({
				type: 'POST',
				url: $(e).attr("action"),
				data: $(e).serialize(),
				success: function(data){$(e).children(".result").html(data);},
				error: function(){$(e).children(".result").html("Save error, please try again.");} // Simple ajax failer msg: should never happen really
			});
			
			// return
			return false;
		});
	});
}




// FILE UPLOADS //
/* I dont like any of the ajax file plugins around, so we will just do normal page submit untill I can find one. 
var ajaxFileUpload = function(){
	$('.ajaxFile').each(function(i, e){
		$(e).submit(function(){
			
			$(e).children(".result").html(busy);
			$(e).children(".result").show();
			
		// Return
		return false;
		
		})
	});
}
*/




// CONVERT TO MODEL BOX //
var model = function(click, element, width, height)
{
	// Dialog It
	$(element).dialog(
	{
		autoOpen:false,
		resizable: false,
		bgiframe: false,
		height: height,
		width: width,
		modal: true
	});
	
	// Button
	$(click).click(function(){
		$(element).dialog('open');
	});

	// Show it
	$(element).css("display","block");
}





// CONVERT TO DATE FOR EXPIRE DATE //
var expireDate = function(e)
{
	$(e).datepicker({dateFormat: 'DD,d MM, yy'});
	
	// Find current date
	var currentDate = $(e).attr('value');
	
	// Check for never and disable if needed
	if (currentDate == "Never") {
		$("#resetToNeverBox").attr("disabled", "disabled");
		$("#resetToNeverBox").attr("checked", "checked");
	}
	
	// Add click to expireDate
	$(e).click(function(){
		$("#resetToNeverBox").attr("disabled", "");
		$("#resetToNeverBox").attr("checked", "");
	})
	
	// Add click to checkbox
	$('#resetToNeverBox').click(function(){
		
		switch($(this).attr("checked"))
		{
			// Checked
			case true :
			currentDate = $(e).attr('value');
			$(e).attr('value','Never');
			break;
			
			// Unchecked
			case false :
			$(e).attr('value',currentDate);
			break;	
		}
	})
}



// FIELD COUNTER //
var fieldCount = function(chrCountIndicatorId, fieldId, coutMax){
		
	// 1st time
	$(chrCountIndicatorId).html(coutMax - $(fieldId).val().length); 
	
	// Key Up
	$(fieldId).keyup(function() // keyup
	{
		var charLength = $(this).val().length;
		$(chrCountIndicatorId).html(coutMax - charLength);
		if (charLength > coutMax){
			$(fieldId).css("color","red");
			$(chrCountIndicatorId).css("color","red");
		}
		else{
			$(fieldId).css("color","");
			$(chrCountIndicatorId).css("color","");
		}
	})
}



// PROV, CITY ARRAY OPTIONS //
var loadCities = function(jsonCityArray, selectedCityId, citySelect, provSelect)
{	
	var doLoadCities = {
		
		init: function(){
			// Empty previous elements
			$(citySelect).empty();
			
			// Check if a provence has been selected
			if ($(provSelect).val() == 0) {
				return;
			}
			
			// Find set according to provence
			var set = $(provSelect).val();
			
			// Loop da loop
			$.each(jsonCityArray[set]['cities'], function(entryIndex, entry){
				
				// Check selected value
				if (entryIndex == selectedCityId) {
				
					// Append Selected option
					$(citySelect).append("<option selected value='" + entryIndex + "'>" + entry + "</option>");
				}
				else {
				
					// Append other options
					$(citySelect).append("<option value='" + entryIndex + "'>" + entry + "</option>");
				}
			});
		}
	}
	
	doLoadCities.init();
	$(provSelect).change(function(){doLoadCities.init();})

};



// SELECTING OF TAGS //
var tagsSelect = function(tagCss, indicator, hiddenTagsField, maxTags){
					
	$(tagCss).each(function(i, tag)
	{
		// Highlight existing selections
		if($(tag).attr('rel') == 1)
		{
			maxTags = maxTags -1
			$(tag).css("background-color","yellow");
		}
		$(indicator).html(maxTags + ' options remaining');
		
		// Add Highlight click function	 
		$(tag).click(function()
		{
			if($(tag).attr('rel') == 0)
			{
				if (maxTags > 0)
				{
					$(tag).attr("rel", "1");
					$(tag).css("background-color", "yellow");
					$(hiddenTagsField).attr("value", $('#tags').attr('value') + $(tag).attr('id') + '-', ''); // remove from tags string
					maxTags = maxTags - 1;
					$(indicator).html(maxTags + ' Tags Left');
					
					$('#tags').change(); // we need to trigger the onchange event so the browsers knows the change has occured.
				}
			}
			else if($(tag).attr('rel') == 1)
			{
				$(tag).attr("rel","0"); // Change rel
				$(tag).css("background-color",""); // Set col
				$(hiddenTagsField).attr("value", $('#tags').attr('value').replace($(tag).attr('id')+'-','')); // remove from tags string
				maxTags = maxTags +1;
				$(indicator).html(maxTags + ' options remaining');
				
				$('#tags').change(); // we need to trigger the onchange event so the browsers knows the change has occured.
			}
		})
	})
}



// COUNT AN ENTRY BEEN CLICKED ON //
// Count a click via an ajax call (banners us this: needs work, should be used for all entries) //
var countClicks = function()
{
	$('.countClick').each(function(i, e){
		$(e).click(function(){
			
			$.ajax(
			{
				type: 'POST',
				url: $(e).attr("rel"),
				data: $(e).serialize()
			});
		})
	})
}





// MODULE SCRIPTS //

	// Front end provence and city dropdowns
	var cityChainSelect = function(url, chainProvenceId, chainStateId, loadingDivId)
	{
		$(chainProvenceId).chainSelect(chainStateId, url,
		{ 
			before:function (target) //before request hide the target combobox and display the loading message
			{ 
				$(loadingDivId).css("display","block");
				$(target).css("display","none");
			},
			after:function (target) //after request show the target combobox and hide the loading message
			{ 
				$(loadingDivId).css("display","none");
				$(target).css("display","inline");
			}
		});
	}
	
	// Menu
	var menu = function()
	{
		$('.menu').each(function(i, e)
		{
			var fade=0.8
			$(e).fadeTo("fast", fade);
	
			 $(e).hover(function ()
			 {
				$(this).fadeTo("fast", 1);
			 }, 
			 function()
			 {
			     $(this).fadeTo("fast", fade);
			 }
			 );
		});	
	} 

	// SearchBox
	var autoCompleteBox = function(options, searchBox)
	{
		$(searchBox).autocomplete(options, 
		{
			//width: 320,
			max: 9,
			selectFirst: false,
			matchContains: true
			//highlight: false,
			//multiple: true,
			//multipleSeparator: ' ',
			//scroll: true,
			//scrollHeight: 300
		});		
	}
	




// LOADS A GOOGLE MAP //
/* Expects a ui dialog to bind to */
var googleMap = function(e, latitude, longitude, address, d)
{
	$(d).bind('dialogopen', function() {
		if (GBrowserIsCompatible()){
			var map = new GMap2(document.getElementById(e));
			var point = new GLatLng(latitude, longitude); 
			map.setCenter((point), 14);
			map.openInfoWindowHtml(map.getCenter(), address);
			map.addOverlay(new GMarker(point));
			map.addControl(new GSmallMapControl());
		}	
	});
}




/* RTE EDITOR */
var rte = function(){
		$('.rte').rte({
		controls_rte: rte_toolbar,
		controls_html: html_toolbar,
		frame_class: 'rteBody',
		height: 800
	});
}





// REQUIRED FIELDS AND CHECKS ETC //
var fieldChecks = function()
{
	// Set Variable
	var numericExpression = /^[0-9]+$/;
	var alertNote = new Array();
	var alertRed = new Array()
	
	// Checks //
		$('.required').blur(function()
		{		
			if (this.value == ''){$(this).addClass("red");}else{$(this).removeClass("red");}
		})
		
		$('.numbers').keyup(function (){
			if ($(this).attr("value").match(numericExpression) || $(this).attr("value").length == 0){noteify($(this), null);}else{noteify($(this),"(Please use only numbers for this field.)");}
		})
	
	// Notify the user
	var noteify = function(e, text)
	{
		// Set and use unique Name
		var eName = $(e).attr("name");
		
		// Tests
		if(text)
		{
			if (!alertNote[eName]) {$(e).after("<div>" + text + "</div><br>"); alertNote[eName] = true;}
			
			if(!alertRed[eName]){$(e).addClass("red"); alertRed[eName] = true;}
		}
		else{
			if (alertRed[eName]) {$(e).removeClass("red"); alertRed[eName] = false;}
		}
	}
}



// UNSAVED CONTENT //
// ads a * to a tab when the user changes content in the admin section
var saveNote = function(name){
	
		var newName = '#tab' + name;
		var newForm = '#form' + name;
		
		$(newForm).change(function(){
			if($('.ui-tabs-selected span').text().charAt(0) != '*'){
				$(newName).prepend('*');
			}
		})
		
}
// SUCCESS RECALL FUNCTIONS //
var runSuccessFunctions = function(fade){

	if(fade){
		$('.success').oneTime(8000, function(){
			$(this).hide("slow");
			$(this).stopTime();
		})	
	}	
	
	// Remove star from active tab
	if($('.ui-tabs-selected span').text().charAt(0) == '*'){
		var tabText = $('.ui-tabs-selected span').text().substring(1);
		$('.ui-tabs-selected span').html(tabText);
	}
}




// TOOLTIP //
var toolTips = function(){

	// Variables
	var tip = null;
	
	// Create It	
	$("body").append('<div id="tool_tip_action">&nbsp;</div>');
	$("#tool_tip_action").css({position: "absolute", "z-index": "1002", "display": "none"});
	
	// Bind it
	$(".tip").bind("mouseenter", function()
	{
		// Set tip and swop
		tip = $(this).attr("title");
		$(this).attr("title", "");
		$("#tool_tip_action").show("fast");
		
	}).bind("mousemove", function(e)
	{
	    $("#tool_tip_action").html(tip).css({"left": e.pageX + 20, "top" : e.pageY + 20});
		
	}).bind("mouseout", function()
	{
		// Swop back and hide
		$(this).attr("title", tip);
	    $("#tool_tip_action").html("").hide().css({"left": -1000, "top" : -1000});
	});  
}


// DOM READY //
$(function()
{
	toolTips();
	fieldChecks();
	countClicks();
	ajaxify();
	
	$("#accordion").accordion();
})
