$(document).ready(function(){

	$('label.customRadio').live("click", customRadio_Click);
	$('label.customCheckbox').live("click", customCheckbox_Click);
	
});


///////////////////////////////
//////     EVENTS        //////
///////////////////////////////

this.CGEvent = {
	WebsiteUser: {
		LOG_IN: "CGEvent-WebsiteUser-LOG_IN",
		LOG_OUT: "CGEvent-WebsiteUser-LOG_OUT"
	}
};


///////////////////////////////
//////    EXTENSIONS     //////
///////////////////////////////

this.Browser = {
	isIE: navigator.userAgent.toLowerCase().indexOf("msie") > -1,
	isFF: navigator.userAgent.toLowerCase().indexOf("firefox") > -1,
	isChrome: navigator.userAgent.toLowerCase().indexOf("chrome") > -1,
	isSafari: navigator.userAgent.toLowerCase().indexOf("safari") > -1,
	Version: $.browser.version
};


Math.roundToHalf = function (value)
{ 
   var converted = parseFloat(value); // Make sure we have a number 
   var decimal = (converted - parseInt(converted, 10)); 
   decimal = Math.round(decimal * 10); 
   
   if (decimal == 5) { return (parseInt(converted, 10)+0.5); } 
   if ( (decimal <= 3) || (decimal >= 7) ) { 
      return Math.round(converted); 
   } else {
      return (parseInt(converted, 10)+0.5); 
   } 
} 


Array.prototype.contains = function(item)
{
	return this.indexOf(item) != -1;
}



Array.prototype.indexOf = function(item)
{
	var retIndex = -1;
	$.each(this, function(i, val)
	{
		if(val == item)
		{
			retIndex = i;
			return false;
		}
	});
	return retIndex;
}


String.prototype.toInt = function()
{
	return parseInt(this);
}

String.prototype.toNumber = function()
{
	return parseFloat(this);
}

String.prototype.maskOut = function(mask)
{
	var start = mask.split("*")[0];
	var end = mask.split("*")[1];
	
	return this.substring(this.indexOf(start)+start.length, this.indexOf(end));
}

String.prototype.maskIn = function(mask, val)
{
	var start = mask.split("*")[0];
	var end = mask.split("*")[1];
	
	var newValue = this.substr(0, this.indexOf(start)+start.length);
	newValue += val;
	newValue += this.substr(this.indexOf(end));
	
	return newValue;
}

String.prototype.isMask = function(mask)
{
	var this_mask = this.split("*")[0];
	this_mask = this_mask.substring( 0, this_mask.indexOf("(") );
	var check_mask = mask;
	
	return this_mask == check_mask;
}

String.prototype.listAppend = function(appendItem, delimeter)
{
	var delim = ",";
	if(delimeter != null)
	{
		delim = delimeter;
	}
	var value = this.listClean(delim).toString();
	var retVal = value;
	if(retVal.listLen(delim) >= 1)
	{
		retVal += delim;
	}
	
	return retVal + appendItem;
}

String.prototype.listRemove = function(removeItem, delimeter)
{
	var delim = ",";
	if(delimeter != null)
	{
		delim = delimeter;
	}
	var value = this.listClean(delim);
	
	var values = value.split(delim);
	var newValue = "";
	for(var i=0; i < values.length; i++)
	{
		var item = values[i];
		if(!newValue.listFind(item) && item != removeItem)
		{
			newValue += item;
			if(i < values.length-1)
			{
				newValue += delim;
			}
		}
	}
	
	return newValue;
}

String.prototype.listClean = function(delimeter)
{
	var delim = ",";
	if(delimeter != null)
	{
		delim = delimeter;
	}
	var thisArr = this.split(delim);
	// loop through array and clean out duplicate items
	var newThis = "";
	for(var i=0; i < thisArr.length; i++)
	{
		var item = thisArr[i];
		if(!newThis.listFind(item))
		{
			newThis += item;
			if(i < thisArr.length-1)
			{
				newThis += delim;
			}
		}
	}
	
	return newThis;
}

String.prototype.listFindNoCase = function(seed, delimeter)
{
	var delim = ",";
	if(delimeter != null)
	{
		delim = delimeter;
	}
	var thisArr = this.toLowerCase().split(delim);
	return thisArr.contains(seed.toLowerCase());
}

String.prototype.listFind = function(seed, delimeter)
{
	var delim = ",";
	if(delimeter != null)
	{
		delim = delimeter;
	}
	var thisArr = this.split(delim);
	return thisArr.contains(seed);
}

String.prototype.listLen = function(delimeter)
{
	var delim = ",";
	if(delimeter != null)
	{
		delim = delimeter;
	}
	
	var len = 0;
	if(this != "")
	{
		len = this.split(delim).length;
	}
	
	return len;
}

String.prototype.toBoolean = function()
{
	return this != null && (this == true || this.toLowerCase() == "true" || this.toLowerCase() == "yes" || parseInt(this) == 1);
}


String.prototype.contains = function(seed)
{
	return this.indexOf(seed) > -1;
}


String.prototype.containsNoCase = function(seed)
{
	return this.toLowerCase().contains(seed.toLowerCase());
}


String.prototype.find = function(seed)
{
	return this.indexOf(seed);
}


String.prototype.findNoCase = function(seed)
{
	return this.toLowerCase().find(seed.toLowerCase());
}

var Url = {};
Url.parse = function()
{
	var href = location.href;
	var data = {};
	data.hash = href.substring( href.find("#") );
	var currentHashes = location.hash.replace(/#/, "").split(";");
	var hashGroups = {};
	for( var i=0; i < currentHashes.length; i++ )
	{
		var hashGroup = currentHashes[i];
		if( hashGroup == "")
		{
			continue;
		}

		var hashGroupKey = hashGroup.substring(0, hashGroup.indexOf("("));
		hashGroups[ hashGroupKey ] = hashGroup.maskOut( hashGroupKey + "(*)" );
	}
	data.hashGroups = hashGroups;
	
	data.fullUrl = data.url = href;
	if( data.url.contains("#") )
	{
		data.url = href.substring( 0, href.find("#") );
	}
	data.domain = href.replace("http://", "");
	data.address = data.domain.substring( 0, data.domain.find("?")-1 );
	data.domain = data.address.split("/")[0];
	data.domain = "http://" + data.domain;
	data.address = "http://" + data.address;
	data.isHomepage = data.domain == data.address;
	data.queryString = data.url.substring( data.url.indexOf("?") ).replace(/\?/ig, "");
	data.queryVariables = {};
	var qvars = String(data.queryString).split("&");
	for( var i=0; i < qvars.length; i++ )
	{
		var pair = qvars[i].split("=");
		data.queryVariables[ pair[0] ] = pair[1];
	}
	
	return data;
};
Url.SetHashGroup = function( key, value )
{
	var newHashObj = {};
	
	var currentHashes = location.hash.replace(/#/, "").split(";");
	for( var i=0; i < currentHashes.length; i++ )
	{
		var hashGroup = currentHashes[i];
		if( hashGroup == "")
		{
			continue;
		}

		var hashGroupKey = hashGroup.substring(0, hashGroup.indexOf("("));
		newHashObj[ hashGroupKey ] = hashGroup.maskOut( hashGroupKey + "(*)" );
	}
	
	// add/edit hash
	newHashObj[key] = value;
	
	// reconstruct hash
	var newHash = "";
	for( var prop in newHashObj )
	{
		newHash += prop + "(" + newHashObj[prop] + ");";
	}
	
	location.hash = newHash;
};
Url.RemoveHashGroup = function( key )
{
	var newHashObj = {};
	
	var currentHashes = location.hash.replace(/#/, "").split(";");
	for( var i=0; i < currentHashes.length; i++ )
	{
		var hashGroup = currentHashes[i];
		if( hashGroup == "")
		{
			continue;
		}

		var hashGroupKey = hashGroup.substring(0, hashGroup.indexOf("("));
		if( hashGroupKey.toLowerCase() == key.toLowerCase() )
		{
			continue;
		}
		newHashObj[ hashGroupKey ] = hashGroup.maskOut( hashGroupKey + "(*)" );
	}
	
	// reconstruct hash
	var newHash = "";
	for( var prop in newHashObj )
	{
		newHash += prop + "(" + newHashObj[prop] + ");";
	}
	
	location.hash = newHash;
	// strip extra hashes from title
	var title = document.title;
	if (title.contains("#")) 
	{
		document.title = title.substring(0, title.findNoCase("#"));
	}
};
Url.HasHashGroup = function( key )
{
	return Url.parse().hashGroups.hasOwnProperty(key);
}

Url.HasAnyHashGroups = function()
{
	var groups = "";
	if( location.href.contains("#") )
	{
		groups = location.href.split("#")[1];
	}
	
	return groups.length > 0;
}
//Url.SetHashGroup( "One", "Four" );
//Url.RemoveHashGroup("One");

///////////////////////////////
//////    UTILITIES      //////
///////////////////////////////


function objectKeys(obj)
{
	var keys = [];
	for(var prop in obj)
	{
		keys.push(prop);
	}
	return keys;
}

function objectHasKey(obj, key)
{
	var keyLower = key.toLowerCase();
	for(var prop in obj)
	{
		if(prop.toLowerCase() == keyLower)
		{
			return true;
		}
	}
	return false;
}

function dumpObject(obj, options)
{
	var output = "";
	for(var prop in obj)
	{
		var propObj = obj[prop];
		if(typeof(propObj) == "object")
		{
			if(options != null && options.hasOwnProperty("recurse") && options.recurse)
			{
				propObj = dumpObject(propObj, true);
			}
			else
			{
				propObj = obj[prop];
			}
		}
		output += prop + ": " + propObj + "\n";
	}
	
	if (options == null || (options != null && (!options.hasOwnProperty("noAlert") || !options.noAlert))) 
	{
		alert(output);
	}
	
	if (options != null && options.hasOwnProperty("doDocumentWrite") && options.doDocumentWrite) 
	{
		document.write(output);
	}
	return output;
}

function getFlashAjaxBridge(name)
{
	if (navigator.appName.toLowerCase().indexOf("microsoft") != -1)
	{
		return window[name];
	}
	else
	{
		return document[name];
	}
}


function getFlashObject(movie)
{
   var returnElement = "";
   
   if (window.document[movie]) {
      returnElement = window.document[movie];
   }
   if (navigator.appName.indexOf("Microsoft Internet")==-1) {
      if (document.embeds && document.embeds[movie]) {
         returnElement = document.embeds[movie]; 
      }
   } else {
      returnElement = document.getElementById(movie);
   }
   
   if(returnElement.length > 1)
   {
   	returnElement = returnElement[0];
   }
   //alert(returnElement.length);
   return returnElement;
}

/*
 *
 	X POSITION (_x) property number= 0
	Y POSITION (_y) property number= 1 
	X SCALE property number= 2 
	Y SCALE property number= 3 
	CURRENTFRAME property number= 4 
	TOTALFRAMES property number= 5
	ALPHA property number= 6
	VISIBILITY property number= 7 
	WIDTH property number= 8
	HEIGHT property number= 9 
	ROTATION property number= 10
	TARGET property number= 11 
	FRAMESLOADED property number= 12
	NAME property number= 13
	DROPTARGET property number= 14
	URL(_url) property number= 15
 */

function getFlashObjectAttribute(movie, attr)
{
	if(typeof(movie) == "string")
	{
		movie = getFlashObject(movie);
	}
	if(movie == null || !movie.hasOwnProperty("TGetProperty"))
	{
		return;
	}
	var propertyMap = {
		x: 0,
		y: 1,
		x_scale: 2,
		y_scale: 3,
		currentFrame: 4,
		totalFrames: 5,
		alpha: 6,
		visibility: 7,
		width: 8,
		height: 9,
		rotation: 10,
		target: 11,
		framesLoaded: 12,
		name: 13,
		dropTarget: 14,
		url: 15
	};
	
	return movie.TGetProperty("/", propertyMap[attr]);
}


///////////////////////////////
//////     CONTROLS      //////
///////////////////////////////

function customRadio_Click(e){
	e.stopImmediatePropagation();
	e.preventDefault();
	var sender = $(this);
	
	// trigger custom event: item has been clicked
	sender.trigger("CGEvent-click");
	// if disabled, clicking does nothing
	if(sender.children('.customRadioHolder.disabled').length > 0)
	{
		return false;
	}
	// trigger custom event: item will be selected but hasn't yet
	sender.trigger("CGEvent-before_select");
	
	//check off the actual input
	var radioBtn = $('#'+ sender.attr('for'));
	radioBtn.attr('checked', "checked");
	
	//uncheck image for all in radio name group
	var radioName = radioBtn.attr('name');
	// deselect radios that aren't the one being selected (hense the "!=" on the ID) but are a part of the same series (checking NAME)
	//var radiosToDeSelect = $('label.customRadio[for!="'+ radioBtn.attr("id") +'"] .customRadioHolder.'+ radioName +'.selected');
	var radiosToDeSelect = $('label.customRadio[for!="'+ radioBtn.attr("id") +'"][name="'+radioName+'"] .customRadioHolder.selected');
	radiosToDeSelect.removeClass('selected');
	radiosToDeSelect.trigger("CGEvent-deselect");
	
	//check image for the new one
	sender.children('.customRadioHolder').addClass('selected');
	sender.trigger("CGEvent-select");
	
	// trigger custom event: item has been successfully selected
	sender.trigger("CGEvent-after_select");
}


function customCheckbox_Click(e){
	e.stopImmediatePropagation();
	e.preventDefault();
	var sender = $(this);

	// trigger custom event: item has been clicked
	sender.trigger("CGEvent-click");
	// if disabled, clicking does nothing
	if(sender.children('.customCheckboxHolder').hasClass('disabled'))
	{
		return false;
	}
	// trigger custom event: item will be selected but hasn't yet
	sender.trigger("CGEvent-before_select");
	
	//check off
	if(sender.children('.customCheckboxHolder').hasClass('selected')){
		var checkId = sender.attr('for');	
		$('#'+checkId+'').removeAttr('checked');
		sender.children('.customCheckboxHolder').removeClass('selected');
		sender.trigger("CGEvent-deselect");
	}
	//check on
	else{
		var checkId = sender.attr('for');
		$('#'+checkId+'').attr('checked', 'checked');
		sender.children('.customCheckboxHolder').addClass('selected');
		sender.trigger("CGEvent-select");
	}
	
	// trigger custom event: item has been successfully selected
	sender.trigger("CGEvent-after_select");
}
