/**
 * Toggle visibility between 'none' and 'inline' an element 'e'
 */
function toggle_visibility(e) 
{
	toggle_style(e, 'none', 'inline');
}

/**
 * Toggle the display style on element 'e' between 'style1' and 'style2'
 */
function toggle_style(e, style1, style2) 
{
	if(document.getElementById(e).style.display == style1 || document.getElementById(e).style.display == '')
	{
		document.getElementById(e).style.display = style2;
	} else 
	{
		document.getElementById(e).style.display = style1;
	}
}

function toggle_help(objA, closedText, openText)
{
	if(objA.innerHTML==closedText)
	{
		objA.innerHTML=openText;
	}
	else
	{
		objA.innerHTML=closedText;
	}

	toggle_visibility('help');
}


/*
 * oneClick() - only allow users to submit a form once
 */
var oneClickFlag = false;
function oneClick(objButton)
{
	if (oneClickFlag == false) {
		oneClickFlag = true;
		setTimeout( 'oneClickDisable("'+objButton.id+'")', 100);
		setTimeout( 'oneClickCallback("'+objButton.id+'")', 5000);
		return true;
	}else{
		return false;		
	}
}

function oneClickDisable(id)
{
	document.getElementById(id).disabled = true;
}

function oneClickCallback(id)
{
	document.getElementById(id).disabled = false;
	oneClickFlag = false;
}
/**
 * Extract everything between <script></script> tags and evaluate it as
 * javascript.
 */
function evalJS(html)
{
	var re = new RegExp('<script[^>]*>([\\S\\s]*?)<\/script>', 'igm'); // assumes
																		// HTML
																		// well
																		// formed
	var match;
	while (match = re.exec(html))
	{
		eval(match[1]);
	}
}

// TODO: encode and decode the options parameter
function AsyncRequest(div, url, options)
{
	this.div = '';

	this.options = 
	{
		data: '',
		method: 'POST'
	};

	this.initialize = function(div, url, options) 
	{
		this.div = div;

		if (options.method)
		{
			if (options.method == "GET")
			{
				this.options.method = "GET";
			}
		}
		
		if (options.formId)
		{
			this.options.data = YAHOO.util.Connect.setForm(options.formId);
		}

		if (options.data)
		{
			this.options.data = options.data;
		}

		YAHOO.util.Connect.asyncRequest(this.options.method, url, this.callback, this.options.data);
	};

	this.evalJS = function(html)
	{
		var re = new RegExp('<script[^>]*>([\\S\\s]*?)<\/script>', 'igm'); // assumes
																			// HTML
																			// well
																			// formed
		var match;
		while (match = re.exec(html))
		{
			eval(match[1]);
		}
	};

	this.handleSuccess = function(o)
	{
		if (o.responseText != null && o.argument.div != '')
		{			
			var div = document.getElementById(o.argument.div);
			var source = o.responseText;
			
			div.innerHTML = source;
			o.argument.evalJS(source);
		}
	};

	this.handleFailure = function(o)
	{
		
	};

	this.callback = 
	{
		success: this.handleSuccess,
		failure: this.handleFailure,
		argument: this
	};

	this.initialize(div, url, options);
};

/**
 * Javascript used to hide/unhide the Options menu. TODO: Get YUI to handle
 * this.
 */
var id = 0;
var z = 1;
var ice = '';
var menuOpen = '';
var hack = '';

function getStyleObj(obj)
{
	if(document.getElementById && document.getElementById(obj))
	{
		return document.getElementById(obj).style;
	} else if (document.all && document.all(obj)) 
	{
		return document.all(obj).style;
	} else if (document.layers && document.layers[obj]) 
	{
		return document.layers[obj];
	} else 
	{
		return false;
	}
}

function chgObjVisibility(mnuItm, newState)
{
	var objstyle = getStyleObj(mnuItm);

	if(objstyle){
		objstyle.display = newState;
		return true;
	} else 
	{
		return false;
	}
}

function showOptions(mnuItm, e)
{
	if(mnuItm == id)
	{
		chgObjVisibility('a' + mnuItm, 'none');
		id = '';
	} else 
	{
		hideMenus();
		z++;
		id = mnuItm;

		var menu = 'a' + mnuItm;
		var obj = 'opt'+ mnuItm;
		document.getElementById(obj).style.zIndex = z;

		if(chgObjVisibility(menu, 'block'))
		{
			e.cancelBubble = true;
			return true;
		} else 
		{
			return false;
		}
	}
}

function usrMenu(mnuItm,div,e,iFrame)
{
	if(mnuItm == menuOpen)
	{
		chgObjVisibility(mnuItm, 'none');
		chgObjVisibility(iFrame, 'none');
		menuOpen ='';
		hack ='';
	} else 
	{
		hideMenus();
		menuOpen = mnuItm;
		hack = iFrame;

		var menu = mnuItm;
		var obj = div;

		document.getElementById(obj).style.zIndex = z;

		if(chgObjVisibility(menu, 'block'))
		{
			chgObjVisibility(iFrame, 'block');
			e.cancelBubble = true;
			return true;
		} else 
		{
			return false;
		}
	}
}

function showMe(mnuItm, e)
{
	if(mnuItm == ice)
	{
		chgObjVisibility(mnuItm, 'none');
		ice = "";
	} else 
	{
		hideMenus();
		ice = mnuItm;

		if(chgObjVisibility(mnuItm, 'block'))
		{
			div = document.getElementById(mnuItm);
			other = document.getElementById('sidebar');
			var h = hitTest(div, other);

			if(h)
			{
				div.style.marginLeft = -155 + 'px';
			}
			e.cancelBubble = true;
			return true;
		} else 
		{
			return false;
		}
	}
}

function hideMenus()
{
	chgObjVisibility('a' + id, 'none');
	chgObjVisibility(ice, 'none');
	chgObjVisibility(menuOpen, 'none');
	chgObjVisibility(hack, 'none');
	ice = '';
	menuOpen = '';
	hack = '';
}

// Initially hide the menus
document.onclick = hideMenus;

/**
 * Add a user to your hotlist from the search results page.
 */
function addToHotList(e, userId)
{
	var e = document.getElementById(e);
} 
 
/**
 * Javascript used save notes for a hot/block/hidden list entry. TODO: Get YUI
 * to handle this.
 */
function saveNote(userId)
{
	document.getElementById('note_button_' + userId).className = 'button_pressed'; 
	document.getElementById('list_notes_status_' + userId).className='saved';
	document.getElementById('list_notes_status_' + userId).innerHTML = 'Note Saved';
}

/**
 * 
 * Javascript functions to communicate with the embedded pixel client to manage
 * invites.
 * 
 */
function new_chat_invite(userId)
{
  var movieName = "pclient2";
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	var pclient2 = (isIE) ? window[movieName] : document[movieName];
	pclient2.newInvite(userId);
}

function accept_chat_invite()
{
	var movieName = "pclient2";
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	var pclient2 = (isIE) ? window[movieName] : document[movieName];
	pclient2.inviteAccepted();
}

function decline_chat_invite()
{
	var movieName = "pclient2";
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	var pclient2 = (isIE) ? window[movieName] : document[movieName];
	pclient2.inviteDeclined();
}


/*
 * swapVisibleDiv Hide all divs with ids in the arrayDivsToHide, and display the
 * div with id displayId
 */
function swapVisibleDiv(displayId, arrayDivsToHide)
{

	// hide all the divs
	for (var i=0; i<arrayDivsToHide.length; i++)
	{
		document.getElementById(arrayDivsToHide[i]).style.display = 'none';
	}

	document.getElementById(displayId).style.display = 'block';
}


function checkAllHotBlockList()
{
	var checkboxes = document.getElementsByName('hot_block_checkbox');

	for(var i = 0; i < checkboxes.length; i++)
	{
		checkboxes[i].checked = true;
	}
}

function uncheckAllHotBlockList()
{
	var checkboxes = document.getElementsByName('hot_block_checkbox');

	for(var i = 0; i < checkboxes.length; i++)
	{
		checkboxes[i].checked = false;
	}
}

var hotblockselectflag = false;

function toggleHotBlockSelect()
{
	if(hotblockselectflag == false)
	{
		checkAllHotBlockList();
		selectedAll();
	}
	else
	{
		uncheckAllHotBlockList();
		unselectedAll();
	}
}

function selectedAll()
{
	
	hotblockselectflag = true;
	document.getElementById('select_all').value = document.getElementById('unselectedHidden').value;
}

function unselectedAll()
{
	hotblockselectflag = false;
	document.getElementById('select_all').value = document.getElementById('selectedHidden').value;
}

function checkHotBlockSelected()
{
	var checkboxes = document.getElementsByName('hot_block_checkbox');
	var count = 0;

	for(var i = 0; i < checkboxes.length; i++)
	{
		if(checkboxes[i].checked)
		{
			count += 1;
		}
	}

	if(checkboxes.length == count)
	{
		selectedAll();
	}
	else
	{
		unselectedAll();
	}
}


 
/**
 * Popup window
 */
var newwindow = new Object();
var newwindowOldWidth = new Object();
var newwindowOldHeight = new Object();

function showTermsPopup(loc) {
	return popUp(loc,660,400,1);	
}

function showPopup(loc) {
	if (loc.indexOf("popup") == -1) {
		if (loc.indexOf("?") == -1) {
			loc += "?popup=popup";
		}else{
			loc += "&popup=popup";
		}
	}
	return popUp(loc,500,300,0);	
}

function showPopupWithScrollbar(loc) {
	if (loc.indexOf("popup") == -1) {
		if (loc.indexOf("?") == -1) {
			loc += "?popup=popup";
		}else{
			loc += "&popup=popup";
		}
	}
	return popUp(loc,500,300,1);
}

function showCustomPopupWithScrollbar(loc, width, height) {
	if (loc.indexOf("popup") == -1) {
		if (loc.indexOf("?") == -1) {
			loc += "?popup=popup";
		}else{
			loc += "&popup=popup";
		}
	}
	return popUp(loc,width,height,1);
}

function popUp(loc, imgWidth, imgHeight, boolScrollbars) {
	return popUpNamed(loc, imgWidth, imgHeight, boolScrollbars, 'ImagePreview');
}

function popUpNamed(loc, imgWidth, imgHeight, boolScrollbars, strName)
{
	imgWidth = parseInt(imgWidth);
	imgHeight = parseInt(imgHeight);
	
	if (newwindow[strName] && !newwindow[strName].closed && newwindow[strName].location) {
		newwindow[strName].location.href = loc;
		var tmpWidth = imgWidth - newwindowOldWidth[strName];
		var tmpHeight = imgHeight - newwindowOldHeight[strName];
		newwindow[strName].resizeBy(tmpWidth,tmpHeight);
		newwindowOldWidth[strName] += tmpWidth;
		newwindowOldHeight[strName] += tmpHeight;
	} else {
	
		var width = screen.width;
		var height = screen.height;
							
		var winLeft = ((width - imgWidth) / 2);
		var winTop = ((height - imgHeight) / 2);
		
		newwindow[strName]=window.open(loc, strName, 'height='+imgHeight+',width='+imgWidth+',left='+winLeft+',right='+winTop+',location=0,scrollbars='+boolScrollbars+',menubar=0,toolbar=0,resizable=0');
		// if (!newwindow.opener) newwindow.opener = self;
		newwindowOldWidth[strName] = imgWidth;
		newwindowOldHeight[strName] = imgHeight;
	}
	if (window.focus) {newwindow[strName].focus()}
	return false;
}

/**
 * Return how many characters are left in a textarea
 */
function text_count(field,cntfield,maxlimit) {
	var cntfield = document.getElementById(cntfield);

	if (field.value.length > maxlimit){ // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
		// otherwise, update 'characters left' counter
	} else{

		if(cntfield.type){
			cntfield.value = maxlimit - field.value.length;
		} else {
			cntfield.innerHTML = maxlimit - field.value.length;
		}
	}
}

/**
 * Function will toggle the visibility of an element
 */
function toggle_visibility(id) {
	var e = document.getElementById(id);
	if (e.style.display == 'block') {
		e.style.display = 'none';
	} else {
		e.style.display = 'block';
	}
}

/**
 * Function will show an element.
 */
function showById(id) {
	var e = document.getElementById(id);
	e.style.display = 'block';
}

/**
 * Function will hide an element.
 */
function hideById(id) {
	var e = document.getElementById(id);
	e.style.display = 'none';
}
/**
 * Jumps to a page
 */
function jump(form) {
	var index = form.view.selectedIndex;

	if (index != 0) {
		url = form.view.options[index].value;
		window.location.assign(url);
	}
}

/**
 * Breaks the frame set, if any.
 */
function breakFrame() {
	if (top.location.href != window.location.href) {
		top.location.href = window.location.href;
	}
}

/**
 * Function should check a the passed in checkbox if this elements contents is
 * not empty, and uncheck it if it is.
 * 
 * @param checkboxId
 *            The ID of the checkbox to check.
 * @param obj
 *            The input box object this will act on.
 */
function checkOther(checkboxId, obj) {
	var objCheckbox = document.getElementById(checkboxId);
	if (obj.value.length > 0) 
	{
		objCheckbox.checked = true;
	}
	else
	{
		objCheckbox.checked = false;
	}
}

 /**
  * Function will check a radio button.
  * 
  * @param radioId
  *            The ID of the radio button to check.
  */
 function checkRadio(radioId) {
 	var obj = document.getElementById(radioId);
 	if (obj) {
 		obj.checked = true;
 	}
 }
 
 
function addToList(){
	values = new Array();
	labels = new Array();
	stored = new Array();
	postData = new Array();
	
	var objCList = document.getElementById('country_list');
	var objBCList = document.getElementById('blocked_list_vis');

	var lTotal = objCList.length;
	
	var exist = false;
	
	// Get the items from the first list, and delete them
	for(var i=lTotal; i>=0; i--){
		if((objCList.options[i] != null) && (objCList.options[i].selected)){
			values.push(objCList.options[i].value);
			labels.push(objCList.options[i].text);			
			stored.push(objCList.options[i].value);
			objCList.remove(i);
		}
	}
	
	// Add the moved items to the second list
	for(var i=0; i<stored.length; i++){
		var exist = arr_srch(values[i],objBCList);
		if(!(exist)){
			var newOpt = document.createElement('option');
			newOpt.text = labels[i];
			newOpt.value = values[i];
			
			try	{
				objBCList.add(newOpt, null);
			}
			catch(ex){
				objBCList.add(newOpt);
			}
		}
	}
	orderList('blocked_list_vis');
	
	var bTotal = objBCList.length;
	for(var i=bTotal; i>=0; i--){
		if (objBCList.options[i] != null) {
			postData.push(objBCList.options[i].value);
		}
	}
	
	$('#blocked_list').val(postData.join(','));
}

function remFromList(){
	values = new Array();
	labels = new Array();
	stored = new Array();
	postData = new Array();
	
	var objCList = document.getElementById('country_list');
	var objBCList = document.getElementById('blocked_list_vis');

	var bTotal = objBCList.length;
	
	var exist = false;
	
	// Get the items from the first list, and delete them
	for(var i=bTotal; i>=0; i--){
		if((objBCList.options[i] != null) && (objBCList.options[i].selected)){
			values.push(objBCList.options[i].value);
			labels.push(objBCList.options[i].text);			
			stored.push(objBCList.options[i].value);
			objBCList.remove(i);
		}
	}
	
	// Add the moved items to the second list
	for(var i=0; i<stored.length; i++){
		var exist = arr_srch(values[i],objCList);
		if(!(exist)){
			var newOpt = document.createElement('option');
			newOpt.text = labels[i];
			newOpt.value = values[i];
			
			try	{
				objCList.add(newOpt, null);
			}
			catch(ex){
				objCList.add(newOpt);
			}
		}
	}
	orderList('country_list');
	
	// Store the post data
	var bTotal = objBCList.length;
	for(var i=bTotal; i>=0; i--){
		if (objBCList.options[i] != null) {
			postData.push(objBCList.options[i].value);
		}
	}
	
	$('#blocked_list').val(postData.join(','));
}

/*
 * Remove the RRated Cover from the image in the gallery
 */
function removeRRatedCover(objImg, imageId, id)
{
	objImg.src = "http://media3.mate1.com/nw/media/thumbnail/"+ imageId;
	objImg.onclick = function(){ loadGalleryImage(id) };
}


/*
 * Function will order a dropdown list
 */
function orderList(objName) {
	// Init vars
	var objList = document.getElementById(objName);
	arrList = new Array();
	
	// Get the data in our list
	var lTotal = objList.length;
	
	for(var a=lTotal-1; a>=0; a--){
		var tmpObj = new Object();
		tmpObj.value = objList.options[a].value;
		tmpObj.text = objList.options[a].text;
		arrList.push(tmpObj);
		objList.remove(a);
	}
	
	// order thelist
	arrList.sort(_orderList);
	
	for(var a=0; a<lTotal; a++){
		var newOpt = document.createElement('option');
		newOpt.value  = arrList[a].value ;
		newOpt.text = arrList[a].text;
		
		try	{
			objList.add(newOpt, null);
		}
		catch(ex){
			objList.add(newOpt);
		}
	}
}

/* Find the values from an array, Required for addToList */
function arr_srch(keyword,arry){
	var f = 0;
	var mx = arry.length - 1;
	var found = false;
	
	while((f <= mx) && (!(found))){
		found = (keyword == arry.options[f].value);
		f++;
	}
	
	if(found){
		return true;
	} else {
		return false;
	}
}

/*
 * Function used for ordering a list
 */
function _orderList(a,b) {
	if (a.text > b.text) {
		return 1;
	}else if (a.text < b.text) {
		return -1;
	}
	return 0;
}


/*
 * Function is called to highlight search results.
 */
function infoBox(obj){
	if (obj.style.background != '#cccccc') {
		obj.style.background = '#cccccc';
		obj.onmouseout = function(){
			obj.style.background = '';
		}
	}
}

/*
 * Function will submit the form with the specified ID
 */
function submitForm(formId) {
	document.getElementById(formId).submit();
}

/*
 * Function will set a value to a form with with a specified id
 */
function setField(id,value) {
	document.getElementById(id).value = value;
}


 /**
  * Returns the levenshtein difference between two strings.
  * Used to find email mispellings.
  * 
  * @param a First string
  * @param b Second string
  * @return The levenshtein difference between the two strings.
  */
 function levenshtein (a, b){
    var min=Math.min, len1=0, len2=0, I=0, i=0, d=[], c='', j=0, J=0;
 
    var split = false;
    try{
        split=!('0')[0];
    } catch(e){
        split=true;
    }
    
    if (a == b) {
        return 0;
    }
    if (!a.length || !b.length) {
        return b.length || a.length;
    }
    if (split){
        a = a.split('');b = b.split('');
    }
    len1 = a.length + 1;
    len2 = b.length + 1;
    d = [[0]];
    while (++i < len2) {
        d[0][i] = i;
    }
    i = 0;
    while (++i < len1) {
        J = j = 0;
        c = a[I];
        d[i] = [i];
        while (++j < len2) {
            d[i][j] = min(d[I][j] + 1, d[i][J] + 1, d[I][J] + (c != b[J]));
            ++J;
        }
        ++I;
    }
    
    return d[len1 - 1][len2 - 1];
}

 /**
  * Function will give suggested domain names to use for your email address.
  * 
  * @param txtEmail The email address to verify.
  * @return false, always
  */
 function emailCheck(obj) {
	 var txtEmail = $(obj).attr('value');
	 var emailDomain = '';
	 if (txtEmail.indexOf('@') <= 0) {
		 return false;
	 }
	 try {
		 emailDomain = txtEmail.substring((txtEmail.indexOf('@')+1),txtEmail.length)
	 } catch(e){
		 return false;
     }
	 if (emailDomain == '') {
		 return false;
	 }
	 var emailDomains = ['yahoo.com', 
	                     'hotmail.com', 
	                     'aol.com', 
	                     'gmail.com', 
	                     'hotmail.co.uk', 
	                     'msn.com', 
	                     'yahoo.co.in', 
	                     'yahoo.co.uk', 
	                     'comcast.net', 
	                     'sbcglobal.net', 
	                     'rediffmail.com', 
	                     'yahoo.ca', 
	                     'live.com', 
	                     'verizon.net', 
	                     'bellsouth.net', 
	                     'yahoo.fr', 
	                     'aim.com', 
	                     'cox.net', 
	                     'earthlink.net', 
	                     'yahoo.com.au', 
	                     'btinternet.com', 
	                     'excite.com', 
	                     'ymail.com', 
	                     'juno.com', 
	                     'netzero.com', 
	                     'charter.net', 
	                     'att.net', 
	                     'peoplepc.com', 
	                     'breakthru.com', 
	                     'shaw.ca', 
	                     'netzero.net', 
	                     'ntlworld.com', 
	                     'live.co.uk', 
	                     'indiatimes.com', 
	                     'netscape.net', 
	                     'bigpond.com', 
	                     'sympatico.ca', 
	                     'rogers.com', 
	                     'mail.ru', 
	                     'rocketmail.com', 
	                     'mail.com', 
	                     'tiscali.co.uk', 
	                     'hotmail.fr', 
	                     'lycos.com', 
	                     'sify.com', 
	                     'optonline.net', 
	                     'googlemail.com', 
	                     'mynet.com', 
	                     'yahoomail.com', 
	                     'live.ca', 
	                     'adelphia.net', 
	                     'yahoo.es', 
	                     'myway.com', 
	                     'telus.net', 
	                     'myspace.com', 
	                     'rediff.com' ];
	 var minLevenshtein = 1000;
	 var minDomain = '';
	 for (domain in emailDomains) {
		 var tmpLevenshtein = levenshtein(emailDomain, emailDomains[domain]);
		 if (minLevenshtein > tmpLevenshtein) {
			 minLevenshtein = tmpLevenshtein;
			 minDomain = emailDomains[domain];
		 }
	 }
	 if ((minLevenshtein > 0) && (minLevenshtein < ((emailDomain.length - 4)/2) )) {
		 $(obj).after("<div class='emailDomainAlert' style='background-color: #FDDFA4; border: 1px solid red; padding: 2px; font-size: 0.85em; position: absolute; margin-left: 50px; display: none;'>Did you mean @" + minDomain + "?</div>");
		 $('.emailDomainAlert').fadeIn('fast', function () { $(this).animate( { opacity: 1 }, 5000,'linear', function () { $(this).fadeOut('slow', function () { $(this).remove(); }); } ); } );
	 }
	 return false;
 }
 
/*
	This function should be called when we try to load an image that didn't make it to the server yet
*/
function imageLoadFailed(obj, level) {
	$(obj).attr('src', 'http://media3.mate1.com/nw/images/nopic/nopic-80-photoup.jpg');
	// Infinite loop anyone?
	level = level + 1;
	if (level < 5) {
		$(obj).unbind("error").error(function () {
			imageLoadFailed(obj, level);
		});
		setTimeout( function () {
			$(obj).attr('src', $(obj).attr('originalSrc') );
		},2000*level);
	}
}

/*
 * Function will preselect our Browser dropdown
 */
function defaultBrowser(obj) {
	if ($(obj).val() > 1) {
		return;
	}
	if ($.browser.msie()) {
		if($.browser.version.number() >= 8) {
			$(obj).val("2");
		}else if($.browser.version.number() >= 7) {
			$(obj).val("3");
		}else if($.browser.version.number() >= 6) {
			$(obj).val("4");
		}else {
			$(obj).val("5");
		}
	}else if ($.browser.firefox()) {
		if($.browser.version.number() >= 3) {
			$(obj).val("6");
		}else if($.browser.version.number() >= 2) {
			$(obj).val("7");
		}else {
			$(obj).val("8");
		}
	}else if ($.browser.safari()) {
		if(parseInt($.browser.version.number()) >= 526) {
			$(obj).val("9");
		}else if(parseInt($.browser.version.number()) >= 419) {
			$(obj).val("10");
		}else {
			$(obj).val("11");
		}
	}else if ($.browser.mozilla()) {
		$(obj).val("12");
	}else if ($.browser.opera()) {
		if($.browser.version.number() >= 9) {
			$(obj).val("13");
		}else {
			$(obj).val("14");
		}
	}else if ($.browser.netscape()) {
		if($.browser.version.number() >= 7) {
			$(obj).val("15");
		} else if($.browser.version.number() >= 6) {
			$(obj).val("16");
		}else {
			$(obj).val("17");
		}
	}else{
		$(obj).val("20");
	}
}

/*
* Function will preselect our OS dropdown
*/
function defaultOS(obj) {
	if ($(obj).val() > 1) {
		return;
	}
	if (navigator.userAgent.indexOf('Windows NT 6.0') != -1) {
		$(obj).val("2");
	} else if (navigator.userAgent.indexOf('Windows NT 5') != -1) {
		$(obj).val("3");
	} else if (navigator.userAgent.indexOf('Windows') != -1) {
		$(obj).val("4");
	} else if (navigator.userAgent.indexOf('Tiger') != -1) {
		$(obj).val("6");
	} else if (navigator.userAgent.indexOf('Mac OS X 10.4') != -1) {
		$(obj).val("7");
	} else if (navigator.userAgent.indexOf('Mac OS X') != -1) {
		$(obj).val("5");
	} else if (navigator.userAgent.indexOf('Mac') != -1) {
		$(obj).val("8");
	} else if (navigator.userAgent.indexOf('Linux') != -1) {
		$(obj).val("9");
	} else {
		$(obj).val("1");
	}
}
	
/*
 *	jQuery startup scripts
 */
$(document).ready(function()
{
	/*
	 * Remove defaults from input boxes.
	 */
     $(".defaultText").focus(function(srcc)
     {
         if ($(this).val() == $(this)[0].title)
         {
             $(this).removeClass("defaultTextActive");
             $(this).val("");
         }
     });
     
     /*
 	 * Add defaults to input boxes.
 	 */
     $(".defaultText").blur(function()
     {
         if ($(this).val() == "")
         {
             $(this).addClass("defaultTextActive");
             $(this).val($(this)[0].title);
         }
     });
     
     $(".defaultText").blur();       
     
     /*
      * Add reload broken images a few times.
      */
     $('.profilePortraitImage').error( function() {
    	 $(this).attr('originalSrc', $(this).attr('src') );
    	 imageLoadFailed(this, 0);
     });
     
     // Selects to checkboxes
     $(".dropDownCheckList").dropdownchecklist( { width: 100 } );
     $(".longDropDownCheckList").dropdownchecklist( { width: 100, maxDropHeight: 200} );
     
     // Browser detection
     defaultBrowser("#browser");
     defaultOS("#operatingSystem");
     
     // Email "did you mean"
     $('#newEmail').blur ( function () { emailCheck(this); } );
     
     
 });

 
 /**
  * Dropdown code
  */
 var timeout    = 500;
 var closetimer = 0;
 var ddmenuitem = 0;

 function jsddm_openClick() {
	$(this).bind('mouseover', jsddm_open);
	$(this).mouseover();

	$(this).find('.bgiframe').bind('click', function(event) { event.stopPropagation(); jsddm_close(); } );
	
	if ($(this).find('.profileOptionsController').attr('href') == '#') {
		return false;
	}
 }
 
 function jsddm_open() {
 	jsddm_canceltimer();
 	jsddm_close();
 	
 	if($(this).closest('div').attr('class') == 'profileOptionsContainer') {
 		$('.profileOptionsContainer').css('z-index','1');
 		$(this).closest('div').css('z-index','2');
		$(this).unbind('click', jsddm_openClick);
		$(this).bind('click', jsddm_close);
		$(this).bind('mouseover', jsddm_open);
 	}
 	ddmenuitem = $(this).find('ul').css('display', 'block');
 }

 function jsddm_close() {
 	if(ddmenuitem) { 
 		ddmenuitem.css('display', 'none');
// 		// Unbind the click ones.
 		$('.profileOptionsContainer > ul > li').bind('click', jsddm_openClick);
 		$('.profileOptionsContainer > ul > li').unbind('click', jsddm_close);
 		$('.profileOptionsContainer > ul > li').unbind('mouseover', jsddm_open);
 	}
 }

 function jsddm_timer() {
 	closetimer = window.setTimeout(function() { jsddm_close() }, timeout);
 }

 function jsddm_canceltimer() {
 	if(closetimer) {
 		window.clearTimeout(closetimer);
 		closetimer = null;
 	}
 }

 $(document).ready( function() {
	 // profile menu
 	$('.profileMenu > li').bind('mouseover', jsddm_open)
 	$('.profileMenu > li').bind('mouseout',  jsddm_timer)
 	// user menu
 	$('.leftMenuContainer > li').bind('mouseover', jsddm_open)
 	$('.leftMenuContainer > li').bind('mouseout',  jsddm_timer)
 	// Options menu (search)
 	$('.profileOptionsContainer > ul > li').bind('click', jsddm_openClick)
 	$('.profileOptionsContainer > ul > li').bind('mouseout',  jsddm_timer)
 	// Top Main Menu 
 	$('#mainMenuContainer > ul > li').bind('mouseover', jsddm_open)
 	$('#mainMenuContainer > ul > li').bind('mouseout',  jsddm_timer)
 	
 	// add google analytics onClick tracking for viewing photos
 	$("a[href*=http://www.mate1.com/nw/gallery/view/]").click(function()
	{
		pageTracker._trackPageview('/click/view_photos/' + getGALocation());
	});

 	// add google analytics onClick tracking for viewing profiles
 	$("a[href*=http://www.mate1.com/nw/profile/view/]").click(function()
	{
		pageTracker._trackPageview('/click/view_profile/' + getGALocation());
	});

 	// add google analytics onClick tracking for sending email
 	$("a[href*=http://www.mate1.com/nw/mail/client#compose]").click(function()
	{
		pageTracker._trackPageview('/click/send_email/' + getGALocation());
	});
 	
 // Show the "message to long" for "essay" blocks.
 	initCharCounters();
 	
 	
 	
 	/* SIMPLE MAIL FUNCTIONS */
 	
 	$("#smFilterView").change(function(){
 		window.location = $(this).children("option:selected").val();
 	});
 	
 	$("#smSelectAll").toggle(function(){
 		$(this).val("Unselect All");
 		$("#inbox .message-checkbox").attr("checked",true);
 	},function(){
 		$(this).val("Select All");
 		$("#inbox .message-checkbox").attr("checked",false); 	
 	});

 /*	
 	$("#smAttachPhoto").click(function(){
 		$(this).addClass("grayed");
 		$(".add-attachment").slideDown();
 		return false;
 	});
 
*/ 
 	$("#smAttachCancel").click(function(){
 		$("#smail_attachment_file").html("<input id=\"attachment_upload\" type=\"file\" name=\"original\" />");		
 		return false;		
 	});

	$("#smail_delete_message_button").click(function(){
		if($(".message-checkbox:checked").length > 0)
		{
			if(confirm("Are you sure you want to delete this message?"))
			{
				$("#smail_delete_message_form").submit();
			}
		}
		else
		{
			alert("There are no messages selected for deletion");
		}
	});

	$("#smail_delete_thread_button").click(function(){
		if($(".message-checkbox:checked").length > 0)
		{
			if(confirm("ATTENTION: You are about to permanently delete all the messages in the selected conversations."))
			{
				if (confirm("This will delete all the messages of the selected conversations.\nConfirm?"))
				{
					$("#smail_delete_thread_form").submit();
				}
			}
		}
		else
		{
			alert("There are no messages selected for deletion");
		}
	});


 });

/** SIMPLE MAILBOX AJAX FUNCTIONS **/

 function requestPhoto(cor_url, clickedButton){
 	
	jQuery.ajax({
	   type: "GET",
	   url: cor_url,
	   success: function(msg){
 		$(clickedButton).addClass("request-sent");	     
	   }
	 });
 }
 
 function hotlistButton(cor_url, clickedButton){
 	
	jQuery.ajax({
	   type: "GET",
	   url: cor_url,
	   success: function(msg){
 		$(clickedButton).addClass("grayed");
 		$(clickedButton).text("Hotlisted");		     
	   }
	 });
 }

 function flirtButton(cor_url, clickedButton){

	jQuery.ajax({
	   type: "GET",
	   url: cor_url,
	   success: function(msg){
 		$(clickedButton).addClass("grayed");
 		$(clickedButton).text("Flirt Sent");		     
	   }
	 });	
 }

 function initCharCounters() {
	 $(".edit_profile_container .essay").not('.ok').addClass('ok').charCounter(1500, {
		 classname: "counter",
		 format: "%1 characters left",
		 container: "<div></div>"
	 });
 }
 
 function unbindMouseOver(obj) {
 	$(obj).parent().parent().parent().unbind('mouseover',jsddm_open);
 	$(obj).parent().parent().parent().find('a.button:first').addClass('buttonDisabled');
 }
 
 function returnFalse() {
	 return false;
 }
 document.onclick = function () { jsddm_close() };

 function getGALocation()
 {
	var pageUrl = document.location.href;
	var strLocation = "default";
	var searchType = /searchType=(.*?)&/i.exec(pageUrl);
	
	if(searchType != null && searchType.length == 2)
	{
		strLocation = searchType[1];
	}
	else if(pageUrl.indexOf("<%= root %>/profile/home") > -1)
	{
		strLocation = "profile_home";
	}
	else if(pageUrl.indexOf("<%= root %>/profile/view") > -1)
	{
		strLocation = "profile_view";
	}
	else if(pageUrl.indexOf("<%= root %>/hotlist") > -1)
	{
		strLocation = "hotlist";
	}
	else if(pageUrl.indexOf("<%= root %>/blocklist") > -1)
	{
		strLocation = "blocklist";
	}
	
	return strLocation;
 }
 
 /**
  * Function will disable all the links on a page
  */
 function disablePage() {
	  $('a').each(function (index) {
		  if ($(this).attr('href').indexOf('popup=popup') == -1) {
			  if ($(this).attr('href').indexOf('?') == -1) {
				  $(this).attr('href',$(this).attr('href') + '?')
			  }else{
				  $(this).attr('href',$(this).attr('href') + '&')
			  }
			  $(this).attr('href',$(this).attr('href') + 'popup=popup')
		  }
	  });
//		 $('a').attr('href','#');
//		 $('a').attr('onclick','javascript: return false;');
 }

var Browser = {
	Version: function() {
		var version = 999; // we assume a sane browser
		if (navigator.appVersion.indexOf("MSIE") != -1)
			// bah, IE again, lets downgrade version number
			version = parseFloat(navigator.appVersion.split("MSIE")[1]);
		return version;
	}
}


function limitText(limitFieldName, limitCount, limitNum) {
  limitField = document.getElementById(limitFieldName);

  if (limitField.value.length > limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
  } else {
    limitCount.value = limitNum - limitField.value.length;
  }
}


