/*******************************************************************************
* This file is part of the "Yagent" project, and may only be used,             *
* modified, and distributed under the terms of the "Yagent" project            *
* license. By continuing to use, modify, or distribute this file you indicate  *
* that you have read the license and understand and accept it fully.           *
*                                                                              *
* Copyright 2007 by the original author or authors                             *
********************************************************************************
SVN: $Id$
*******************************************************************************/

var Yagent = {
	version : '$Rev$'
};

/**
 * Initializes page
 */
function _initialize()
{
	if (window['onPageLoad'] != undefined) {
		window['onPageLoad']();
	}
	
	LoadBMS();
	preloadImages();
}

/**
 * Reloads current page with the new
 * content language selected. Performs checking if specified language
 * is locked or unavaiable to display
 */
function changeSiteLanguage()
{
	var cl_select = document.getElementById('cl');
	var cl_selected = cl_select.options[cl_select.selectedIndex];
	
	if (!cl_select || cl_selected.disabled) {
		alert(locale['LANGUAGE_NOT_AVAIL']);
		return;
	}
	
	var locHref = location.href;
	
	if (locHref.match(/\?/)) {
		locHref = locHref.replace(/cl=\w{2}_\w{2}\&?/g, '');
		locHref = locHref.replace(/\&+$/, '');
		locHref += '&cl=' + cl_select.value;
	} else {
		locHref += '?cl=' + cl_select.value;
	}
	
	location.href = locHref;
	return;
}

/**
 * Swaps values in two inputs. Returns false if values is equals
 * @return boolean
 */
Yagent.swapInputValues = function (input1, input2)
{
	if (input1.value == input2.value) {
		return false;
	}
	
	var vt = input1.value;
	input1.value = input2.value;
	input2.value = vt;
	
	return true;
};

/**
 * Fixes citizenship values
 * @return void
 */
Yagent.fixCitizenshipValues = function (frm)
{
	if (frm['citizenship1'].value == 'null')
	{
		Yagent.swapInputValues(frm['citizenship1'], frm['citizenship2']);
		Yagent.swapInputValues(frm['citizenship2'], frm['citizenship3']);
		
		if (frm['citizenship1'].value == 'null') {
			Yagent.swapInputValues(frm['citizenship1'], frm['citizenship2']);
		}
	}
};

/**
 * Fixes spoken values
 * @return void
 */
Yagent.fixSpokenValues = function (frm)
{
	if (frm['spoken1'].value == 'null')
	{
		Yagent.swapInputValues(frm['spoken1'], frm['spoken2']);
		Yagent.swapInputValues(frm['spoken2'], frm['spoken3']);
		
		if (frm['spoken1'].value == 'null') {
			Yagent.swapInputValues(frm['spoken1'], frm['spoken2']);
		}
	}
};

/**
 * Shows popup window with specified location
 */
function showPopupWindow(windowName, href, wWidth, wHeight, scrollable, resizable)
{
	if (this[windowName] != null && this[windowName].closed) {
		this[windowName] = null;
	}

	var wndWidth  = (wWidth  != undefined) ? wWidth  : 360;
	var wndHeight = (wHeight != undefined) ? wHeight : 280;

	if (this[windowName]) {
		this[windowName].focus();
		return true;
	}

	var leftPos = (screen.width  - wndWidth) / 2;
	var topPos  = (screen.height - wndHeight) / 2 - 20;
	var features = 'toolbar=no, location=no, directories=no, menubar=no, scrollbars=' + (scrollable ? 'yes' : 'no') + ', resizable=' + (resizable ? 'yes' : 'no') + ', status=no, width=' + wndWidth + ', height=' + wndHeight + ', top=' + topPos + ',left=' + leftPos;

	this[windowName] = window.open(href, windowName, features);
	this[windowName].focus();

	return true;
}

/**
 * Handler for "Same as contact"
 */
Yagent.onCopyFromContactClick = function(obj)
{
	frm = obj.form;
	
	var locationRow1 = document.getElementById('locationRow1');
	var locationRow2 = document.getElementById('statesSelectRow');
	
	if (obj.checked)
	{
		locationRow1.style.display    = 'none';
		locationRow1.style.visibility = 'hidden';
		
		if (locationRow2['_shouldBeVisible'] == true) {
			locationRow2.style.display    = 'none';
			locationRow1.style.visibility = 'hidden';
		}
		
	} else
	{
		locationRow1.style.display    = '';
		locationRow1.style.visibility = '';
		
		if (locationRow2['_shouldBeVisible'] == true) {
			locationRow2.style.display    = '';
			locationRow1.style.visibility = '';
		}
	}
};

/** *** */
Yagent.formatFileSize = function (fileSize)
{
	if (typeof fileSize == 'undefined' || !fileSize || fileSize == null) {
		return '-';
	}
	
	fileSize = 0 + fileSize;
	
	if (fileSize > 1024) {
		return (fileSize/1024).toFixed(2) + locale['LABEL_KBYTES'];
	} else if (fileSize > 1048576) {
		return (fileSize/1048576).toFixed(2) + locale['LABEL_MBYTES'];
	} else {
		return fileSize + locale['LABEL_BYTES'];
	}
};

/** *** */
Yagent.testPasswordStrength = function(pwdValue, strMessageId)
{
	var res = 0;
	var strRes = locale['PW_VERY_WEAK'];
	var pl = pwdValue.length;
	
	if (pwdValue == null || typeof(pwdValue) == 'undefined')
	{
		return 0;
	}
	
	// Length
	
	if      (pl > 3 && pl < 8)  { res += 6  }
	else if (pl > 7 && pl < 16) { res += 22 }
	else if (pl > 15)           { res += 18 }
		
	if (pwdValue.match(/[a-z]/))   { res += 1 }
	if (pwdValue.match(/[A-Z]/))   { res += 5 }
	if (pwdValue.match(/\d+/))     { res += 5 }
	if (pwdValue.match(/\d{3,}/))  { res += 5 }
		
	if (pwdValue.match(/.[!,@,#,$,%,^,&,*,?,_,~]/)) { res += 5 }
	if (pwdValue.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) { res += 5 }
	if (pwdValue.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) { res += 2 }
	if (pwdValue.match(/([a-zA-Z])/) && pwdValue.match(/([0-9])/)) { res += 2 }
	if (pwdValue.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/)) { res += 2 }
	
	if (res < 16)                  { strRes = locale['PW_VERY_WEAK'] }
	else if (res > 15 && res < 25) { strRes = locale['PW_WEAK'] }
	else if (res > 24 && res < 35) { strRes = locale['PW_REASONABLE'] }
	else if (res > 34 && res < 45) { strRes = locale['PW_STRONG'] }
	else                           { strRes = locale['PW_VERY_STRONG'] }
		
	res = Math.round((res/40)*100);
	res = Math.max(  0, res);
	
	if (strMessageId != null) {
		var messageElement = document.getElementById(strMessageId);
		messageElement.innerHTML = strRes;
	}
	
	return Math.min(100, res);
}

function changeListSort(prefix, sortId)
{
	var tab;
	var content;
	var sorts = ['create_date', 'view_count', 'profile_completeness',
		'site', 'club', 'trans', 'video_rate', 'new', 'all', 'update_date',
		'Players', 'Clubs', 'Coaches', 'Fans', 'Videos'
	];
	
	for (var i = 0; i < sorts.length; i++)
	{
		tab = document.getElementById(prefix + '_tab_' + sorts[i]);
		if (tab) {
			tab.className = tab.className.replace(/On/, 'Off');
		}

		content = document.getElementById(prefix + '_content_' + sorts[i]);
		if (content) {
			content.style.visibility = 'hidden';
			content.style.display = 'none';
		}
	}
	
	tab = document.getElementById(prefix + '_tab_' + sortId);
	if (tab) {
		tab.className = tab.className.replace(/Off/, 'On');
	}

	content = document.getElementById(prefix + '_content_' + sortId);
	if (content) {
		content.style.visibility = 'visible';
		content.style.display = 'block';
	}
}

function pAfterAddFavourite(objId)
{
	setTextContent(this, locale['LABEL_FROM_FAVOURITES']);
	this.onclick = function () {
		new AjaxDataBearer('/Yagent_Controller_ProfileFavourites/DelFavourite', {favId: objId}, 'accountMenuContainer', delegate(this, pAfterDelFavourite, [objId])).Execute();
		return false;
	}
	this.setAttribute('onclick', "new AjaxDataBearer('/Yagent_Controller_ProfileFavourites/DelFavourite', {favId: '" + objId + "'}, 'accountMenuContainer', delegate(this, pAfterDelFavourite, ['" + objId + "'])).Execute(); return false;");
	copyPopupContent(objId);
	if (window['afterAddFavourite']) {
		afterAddFavourite();
	}
}

function pAfterDelFavourite(objId)
{
	setTextContent(this, locale['LABEL_TO_FAVOURITES']);
	this.onclick = function () {
		new AjaxDataBearer('/Yagent_Controller_ProfileFavourites/AddFavourite', {favId: objId}, 'accountMenuContainer', delegate(this, pAfterAddFavourite, [objId])).Execute();
		return false;
	}
	this.setAttribute('onclick', "new AjaxDataBearer('/Yagent_Controller_ProfileFavourites/AddFavourite', {favId: '" + objId + "'}, 'accountMenuContainer', delegate(this, pAfterAddFavourite, ['" + objId + "'])).Execute(); return false;");
	copyPopupContent(objId);
	if (window['afterDelFavourite']) {
		afterDelFavourite();
	}
}

function preloadImages()
{
	var docImages = document.getElementsByTagName('IMG');
	document.pageImages = new Array();
	
	for (var i = 0; i < docImages.length; i++) {
		var myImage = new Image();
		myImage.src = docImages[i].src;
		document.pageImages.push(myImage);
	}
}


function copyPopupContent(objId)
{
	var sourcePopup = document.getElementById('overDiv');
	var targetPopup = document.getElementById('popupDiv' + objId);
	if (sourcePopup && targetPopup)
	{
		targetPopup.innerHTML = sourcePopup.innerHTML;
	}
}

function isCreditCard(CC)
{
	if (CC.length > 19) {
		return (false);
	}

	var sum = 0;
	var mul = 1;
	var l = CC.length;
	
	for (var i = 0; i < l; i++)
	{
		var digit = CC.substring(l-i-1,l-i);
		var tproduct = parseInt(digit ,10) * mul;
		if (tproduct >= 10) {
			sum += (tproduct % 10) + 1;
		} else {
			sum += tproduct;
		}
		if (mul == 1) {
			mul++;
		} else {
			mul--;
		}
	}

	if ((sum % 10) == 0) {
		return true;
	} else {
		return (false);
	}
}

function isVisa(cc)
{
	if ((cc.substring(0, 1) == 4) && (cc.length == 16) || (cc.length == 13)) {
		return isCreditCard(cc);
	}
	return false;
}

function isMC(cc)
{
	if ((cc.length == 16) && (cc.substring(0, 2) == 51) || (cc.substring(0, 2) == 52) || (cc.substring(0, 2) == 53) || (cc.substring(0, 2) == 54) || (cc.substring(0, 2) == 55)) {
		return isCreditCard(cc);
	}
	return false;
}

function isAmex(cc)
{
	if ((cc.length == 15) && (cc.substring(0, 2) == 34) || (cc.substring(0, 2) == 37)) {
		return isCreditCard(cc);
	}
	return false;
}

function isDiscover(cc)
{
	if ((cc.length == 16) && (cc.substring(0, 4) == 6011))
	{
		return isCreditCard(cc);
	}
	return false;
}

function checkCard(type, cc) {
	return (
		(type == 'Amex' && isAmex(cc)) || 
		(type == 'Visa' && isVisa(cc)) ||  
		(type == 'MasterCard' && isMC(cc)) || 
		(type == 'Discover' && isDiscover(cc))
	);
}

function LoadBMS()
{
	var USP = document.getElementById('BMS-usp');
	var USPContent = document.getElementById('BMS-usp-content');
	if (USPContent!=null) {
		USPContent.innerHTML = '&nbsp;';
		USP.style.display = '';
		var w = USPContent.clientWidth;
		USP.style.display = 'none';
		USPContent.innerHTML = '';
		new AjaxDataBearer('/Yagent_Controller_Utils/GetBMS', {scrwidth: w, scrheight: screen.height, layout: 'UNDER-SEARCH-PANEL'},'BMS-usp-content',ShowBMS_UPS).Execute(true);
	}
	
	var UPP = document.getElementById('BMS-upp');
	var UPPContent = document.getElementById('BMS-upp-content');
	if (UPPContent!=null) {
		UPPContent.innerHTML = '&nbsp;';
		UPP.style.display = '';
		var w = 200;//UPPContent.clientWidth;
		UPP.style.display = 'none';
		UPPContent.innerHTML = '';
		new AjaxDataBearer('/Yagent_Controller_Utils/GetBMS', { layout: 'UNDER-PROFILE-PANEL'},'BMS-upp-content',ShowBMS_UPP).Execute(true);
	}
	
}

function clickBMS(id){
	new AjaxDataBearer('/Yagent_Controller_Utils/ClickBMS', {clickid: id}).Execute(true);
}

function ShowBMS_UPS()
{	
	var USPContent = document.getElementById('BMS-usp-content');
	if (USPContent.innerHTML != '') {
		document.getElementById('BMS-usp').style.display = '';
		document.getElementById('BMS-usp-close').style.display = '';
	}
}

function ShowBMS_UPP()
{	
	var USPContent = document.getElementById('BMS-upp-content');
	if (USPContent.innerHTML != '') {
		document.getElementById('BMS-upp').style.display = '';
		USPContent.style.display = '';
	}
}


function HideBMS_UPS(CH,Step)
{
	var USP = document.getElementById('BMS-usp');
	var USPCont = document.getElementById('BMS-usp-content');
	var USPClose = document.getElementById('BMS-usp-close');
	var USPTable = document.getElementById('BMS-usp-table');
	if (CH == null) {
		CH = USPCont.clientHeight;
		Step = 4;
	} 
	
	if (CH > 0) {
		if (CH < 50) Step = 5;
		if (CH < 40) Step = 6;
		if (CH < 30) Step = 8;
		if (CH < 15) Step = 15;
		var H = CH -Step;
		if (H < 0)
			H = 0;
		USPCont.style.height = H+'px';
		USPClose.style.height = H+'px';
		USPTable.style.height = H+'px';
		if (H == 0) 
			var timeout = 1;
		else
			var timeout = 8;
		setTimeout('HideBMS_UPS('+(CH-Step)+','+Step+')',timeout);
			
	} else {
		USP.style.display = 'none';
		USPTable.style.display = 'none';
	}
	return false;
}
