﻿//This function checks the array to tell if this country requires only postcode as mandatory field
function IsPostCodeSearch(CountryName)
{
	var flag = false;
	
	for(var i=0; i < PostCodeSearchArray.length; i++)
	{
		if(CountryName == PostCodeSearchArray[i])
		{
			flag = true;
			break;
		}
	}
	return flag;
}

//'Purpose : This function is for default enter button.
function TrapEnter_onkeypress(e, btnID) 
{
	var submitButton = document.getElementById(btnID);
	var key;
	
	if (window.event)  
		key = event.keyCode 
	else  
		key = e.which  

	if (key == 13)
	{
		if (window.event) //IE 
		{   
			window.event.returnValue = null; 
			window.event.cancel = true;
		}  
		else
		{
			e.cancel = true;
			e.returnValue = false;
		}
			
		if(typeof submitButton.click == 'undefined') //To take case of FF
		{
			//alert('its undef');
		}
		else
			submitButton.click();

		return false;
	}
 }

function ValidateTime(controlID) 
{
	var strMessage="";
	if(document.getElementById(controlID))
	{
		if(trim(document.getElementById(controlID).value)=='') 
			strMessage="Please enter time";
		else
		{
			var Val = document.getElementById(controlID).value.split(":");
			if(parseInt(Val[0])>23 || parseInt(Val[1])>59)
				strMessage="Please enter valid time";
		}
	}     
	return strMessage;
}
		  
function CheckFilled(thisTxt, divValId) 
{
	var divVal = document.getElementById(divValId);

	if (trim(thisTxt.value)=='')
		divVal.innerHTML='*';
	else
		divVal.innerHTML='';
}
	 
//'Purpose : This function will remove the space bgining n End of input value
function trim(val)
{
	if(val!=null)
	{
		var val1 = val;
		val1=val1.replace(/^\s*|\s*$/g,"");
		return val1;						   
	}
	return '';
}

//<!--
function numbersonly(e)
{
	var key;
	var keychar;

	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);
	
	// control keys
	if ((key==null) || (key==0) || (key==8) ||
		(key==9) || (key==13) || (key==27) || (key==46))
	   return true;

	// numbers
	else if ((("0123456789").indexOf(keychar) > -1))
	   return true;
	else
	   return false;
}


function numbers_and_dot_only(ctl,e)
{
	var key;
	var keychar;

	
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	   
	keychar = String.fromCharCode(key);
	

	// control keys
	if ((key==null) || (key==0) || (key==8) ||
		(key==9) || (key==13) || (key==27) )
	   return true;

	// numbers
	else if ((("0123456789.").indexOf(keychar) > -1))
	{
		if((ctl.value.indexOf(".")>-1) && ((".").indexOf(keychar) > -1)) //added by devis to check only one decimal is allowed.
			return false;
		else
			return true;
	}
	else
	   return false;
}

//-->
//******************************************************************
//'Purpose : To Check at least one day is selected for playing on
//*****************************************************************/	

	function ValidatePlayingOn(MorningCheckBox,AfterNoonCheckBox,EveninigCheckBox)
	{
		var chkBoxList = document.getElementById(MorningCheckBox);
		var list = chkBoxList.getElementsByTagName("input");
		for(i = 0; i <  list.length; i++)
		{
			if(list[i].type == "checkbox")
			{
				if(list[i].checked)
				{
					return "";
				}
			}
		}
		chkBoxList = document.getElementById(AfterNoonCheckBox);
		list = chkBoxList.getElementsByTagName("input");
		for(i = 0; i <  list.length; i++)
		{
			if(list[i].type == "checkbox")
			{
				if(list[i].checked)
				{
					return "";
				}
			}
		}
		chkBoxList = document.getElementById(EveninigCheckBox);
		list = chkBoxList.getElementsByTagName("input");
		for(i = 0; i <  list.length; i++)
		{
			if(list[i].type == "checkbox")
			{
				if(list[i].checked)
				{
					return "";
				}
			}
		}
	   return "Please select at least one day for playing on \n\r ";
	}
	/*Toggle the  control displays if already visible then make it invisble and vice versa..*/
	function ShowHideToggle(Ctl)
	{
		var control= document.getElementById(Ctl);
		if(control.style.display=="none")
			control.style.display = "inline";
		else
			control.style.display = "none";
		
	}

	/*Show control*/
	function Show(Ctl)
	{
		var control= document.getElementById(Ctl);
		control.style.display = "inline";
	}

	/*Hide the  control..*/
	function Hide(Ctl)
	{
		var control= document.getElementById(Ctl);
		control.style.display = "none";
		
	}
	/*Function to display Div in center of screen*/
	function showdeadcenterdiv(DivID) 
	{
		var myWidth = 0, myHeight = 0;
		if( typeof( window.innerWidth ) == 'number' ) 
		{
			//Non-IE
			myWidth = window.innerWidth;
			myHeight = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) 
		{
			//IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) 
		{
			//IE 4 compatible
			myWidth = document.body.clientWidth;
			myHeight = document.body.clientHeight;
		}
		var CenterDiv = document.getElementById(DivID);
		if(CenterDiv)
		{
			var x = (myWidth/ 2);
			var y = (myHeight/ 2);  
			CenterDiv.style.top = y+'px';
			CenterDiv.style.left = x+'px';
		}
	} 

//******************************************************************
//'Function : isSpecialCharacter
//'Purpose : This function is used to validate user name not allowing special characters
//*****************************************************************/	
/*	function isSpecialCharacter(id)
	{
		//"!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
		var SpeciExpression = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
		
		for (var i = 0; i < id.value.length; i++)
		{
			if (SpeciExpression.indexOf(id.value.charAt(i)) != -1)
			{
				alert("wrong");
				return false;
			}
			else
			{
				alert("right");
				return true;
			}    
		}
		
	}*/
//******************************************************************
//'Function : RestrictMaxLength
//'Purpose : This function is used to restrict user to enter charater than max legth allowed
//'Created By: Devis on 06 Jan 2009
//*****************************************************************/	
function RestrictMaxLength(ctl,e,Maxlength)
{
	var key;
	var keychar;
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	   
	// control keys
	if ((key==null) || (key==0) || (key==8) ||
		(key==9) || (key==13) || (key==27) )
	   return true;

	if(ctl.value.length>=Maxlength) 
		return false;
	else
		return true;
}

var ns4 = (navigator.appName.indexOf("Netscape")>=0 
		  && parseFloat(navigator.appVersion) >= 4 
		  && parseFloat(navigator.appVersion) < 5)? true : false;
var ns6 = (parseFloat(navigator.appVersion) >= 5 
		  && navigator.appName.indexOf("Netscape")>=0 )? true: false;
var ns = (document.layers)? true:false;
var ie = (document.all)? true:false;

function getElLeft(el) {
	if (ns4) {return el.pageX;} 
	else {
		xPos = el.offsetLeft;
		tempEl = el.offsetParent;
		while (tempEl != null) {
			xPos += tempEl.offsetLeft;
			  tempEl = tempEl.offsetParent;
		}
		return xPos;
	}
}
function getElTop(el) {
	if (ns4) {return el.pageY;} 
	else {
		yPos = el.offsetTop;
		tempEl = el.offsetParent;
		while (tempEl != null) {
			yPos += tempEl.offsetTop;
			  tempEl = tempEl.offsetParent;
		}
		return yPos;
	}
}

function gotoTop(xpos,controlId,evt)
	{   
		var el = document.getElementById(controlId);
		window.scrollTo(0,0);
		window.scrollTo(0,xpos);
		//alert(el.screenTop);      
		//window.scrollTo(0,(evt.clientY + 10));
	}
//Function to get all selected checkbox for day
function GetallcheckedValuesfromCheckboxlist(CheckboxlistID)
{
	var SelectedValues=''; // SelectedValues are seperated by , 
	var Checkboxlist = document.getElementById(CheckboxlistID);
	var List = Checkboxlist.getElementsByTagName("input");
	for(i = 0; i <  List.length; i++)
	{
		if(List[i].type == "checkbox")
		{
			if(List[i].checked) 
			{
				SelectedValues=SelectedValues + List[i].value + ', '
			}
		}
	}
	if(SelectedValues!='')
			SelectedValues= SelectedValues.substring(0, SelectedValues.length - 2); 
	return SelectedValues;
}
//******************************************************************
//'Purpose : This function is used to disable Anchor button
//'Created By: Devis on 06 Feb 2010
//*****************************************************************/
function disableAnchorButton(buttonID) 
{
	var href = buttonID.getAttribute("href");
	if(href && href != "" && href != null)
	{
	   buttonID.setAttribute('href_bak', href);
	}
	buttonID.removeAttribute('href');
	buttonID.style.color="gray";
}        
//******************************************************************
//'Purpose : This function is used to disable control
//'Created By: Devis on 06 Feb 2010
//*****************************************************************/
function disableButton(buttonID) 
{
	document.getElementById(buttonID).disabled = true;
}          
//******************************************************************
//'Purpose : This function is used to validate Email Address
//'Created By: Devis on 08 Feb 2010
//*****************************************************************/
function EmailValidation(textbox) 
{
		if(document.getElementById(textbox))
		{
			var str=trim(document.getElementById(textbox).value);
			if(str!="")
			{
				var at="@"
				var dot="."
				var lat=str.indexOf(at)
				var lstr=str.length
				var ldot=str.indexOf(dot)
				if (str.indexOf(at)==-1){
				   alert("Invalid E-mail ID")
				   document.getElementById(textbox).focus();
				   return false
				}

				if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
				   alert("Invalid E-mail ID")
				   document.getElementById(textbox).focus();
				   return false
				}

				if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
					alert("Invalid E-mail ID")
					document.getElementById(textbox).focus();
					return false
				}

				 if (str.indexOf(at,(lat+1))!=-1){
					alert("Invalid E-mail ID")
					document.getElementById(textbox).focus();
					return false
				 }

				 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
					alert("Invalid E-mail ID")
					document.getElementById(textbox).focus();
					return false
				 }

				 if (str.indexOf(dot,(lat+2))==-1){
					alert("Invalid E-mail ID")
					document.getElementById(textbox).focus();
					return false
				 }
				
				 if (str.indexOf(" ")!=-1){
					alert("Invalid E-mail ID")
					document.getElementById(textbox).focus();
					return false
				 }
			}
			return true					

		}
		 return true					
}
//******************************************************************
//'Purpose : This function is used to get date from datetext
//'Created By: Devis on 13 Feb 2010
//*****************************************************************/
function returndate(DateText)
{
	var SelectedExpiredDate=DateText;
	var arr=new Array();
	arr=SelectedExpiredDate.split("-");
	var SelectedtedDate=new Date();
	if(arr[2].indexOf(" ")>-1)
	{
		var year=arr[2].substring(0,arr[2].indexOf(" "));
	}
	else
	{
		var year=arr[2];
	}
	var day;
	var monthstr;
	if(!(isNaN(arr[1])))
	{
		monthstr=arr[0];
		day=arr[1];
	}
	else
	{
		monthstr=arr[1];
		day=arr[0];
	}
	var month;
	switch(monthstr)
	{
		case 'Jan':
			month=1;
			break;
		case 'Feb':
			month=2;
			break;
		case 'Mar':
			month=3;
			break;
		case 'Apr':
			month=4;
			break;
		 case 'May':
			month=5;
			break;
		case 'Jun':
			month=6;
			break;
		case 'Jul':
			month=7;
			break;
		 case 'Aug':
			month=8;
			break;
		 case 'Sep':
			month=9;
			break;
		case 'Oct':
			month=10;
			break;
		case 'Nov':
			month=11;
			break;
		case 'Dec':
			month=12;
			break;
	}
	SelectedtedDate.setFullYear(year,month-1,day);
	return SelectedtedDate;
}   
//******************************************************************
//'Purpose : This function is used to display Help on and off
//'Created By: Devis on 24 Feb 2010
//*****************************************************************/
function showHideHlp()
{
	if(document.getElementById('divHelp'))
	{
		if (document.getElementById('divHelp').style.display == "none")
		{
			//document.getElementById('divHelp').style.display = "block";
			//ctl.innerHTML = "Switch Tips Off"
			//ctl.classname = "tips-off sprite"
			if(document.getElementById('imgOnOff')) document.getElementById('imgOnOff').src='../images_sys/SiteImages/off.png';
			$("#divHelp").show("normal");

		}
		else 
		{
			//document.getElementById('divHelp').style.display = "none";
			//ctl.innerHTML = "Switch Tips On"
			//ctl.classname = "tips sprite"
			if(document.getElementById('imgOnOff')) document.getElementById('imgOnOff').src='../images_sys/SiteImages/on.png';
			$("#divHelp").hide("normal");
		}
	}
	return false;
}
//******************************************************************
//'Purpose : This function is used to Round passed number
// num : passed number //dec : up to how many decimal point
//'Created By: Jony
//*****************************************************************/
function RoundNumber(num, dec) 
{
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

//******************************************************************
//'Purpose : This function is used to check record is selected from list control or not
//'Created By: Rekansh
//*****************************************************************/
function fnValidateCheckBoxCheckInListControl(ListControlClintId, Message)
{
	var tbl = document.getElementById(ListControlClintId)
	if(tbl == null)
	{
		alert(Message);
		return false;
	}
	else
	{
		var inputs = tbl.getElementsByTagName("input"); //Retrieve all the input elements from the grid
		var isValid = false;
		for (var i=0; i < inputs.length; i += 1) { //Iterate over every input element retrieved
			if (inputs[i].type === "checkbox") { //If the current element's type is checkbox, then it is wat we need
				if(inputs[i].checked === true) { //If the current checkbox is true, then at least one checkbox is ticked, so break the loop
				   return true;
				}
			}
		}
		alert(Message);
		return false;
	}
}

/*Date extender to get users timezone ofset*/
Date.prototype.stdTimezoneOffset = function () {
	var jan = new Date(this.getFullYear(), 0, 1);
	var jul = new Date(this.getFullYear(), 6, 1);
	return -Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset())/60;
}

Date.prototype.dst = function () {
	return this.getTimezoneOffset() < this.stdTimezoneOffset();
}

function jeval(str) { return eval('(' + str + ')') }


/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/

jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined' || (name && typeof name != 'string')) { // name and value given, set cookie
        if (typeof name == 'string') {
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = name + '=' + encodeURIComponent(value) + expires + path + domain + secure;
        } else { // `name` is really an object of multiple cookies to be set.
            for (var n in name) { jQuery.cookie(n, name[n], value || options); }
        }
    } else { // get cookie (or all cookies if name is not provided)
        var returnValue = {};
        if (document.cookie) {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (!name) {
                    var nameLength = cookie.indexOf('=');
                    returnValue[cookie.substr(0, nameLength)] = decodeURIComponent(cookie.substr(nameLength + 1));
                } else if (cookie.substr(0, name.length + 1) == (name + '=')) {
                    returnValue = decodeURIComponent(cookie.substr(name.length + 1));
                    break;
                }
            }
        }
        return returnValue;
    }
};
function getcarret(input) {
    if (!$.browser.msie) return { start: input.selectionStart, end: input.selectionEnd };
    var pos = { start: 0, end: 0 },
					range = document.selection.createRange();
    pos.start = 0 - range.duplicate().moveStart('character', -100000);
    pos.end = pos.start + range.text.length;
    return pos;
}


///Favourite players toggle
var Favourites = new function ()
{
    var _el;
    var _onImage;
    var _offImage;

    this.ToggleFavTeam = function (teamID, userID, el, onImage, offImage)
    {
        _el = $(el);
        _onImage = onImage;
        _offImage = offImage;

        $.ajax({
            type: "POST",
            url: "/ws/ws.asmx/ToggleFav",
            data: "{'objType':'team','objID':'" + teamID + "','PlayerID':'" + userID + "'  }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg)
            {
                toggleTickbox(msg.d);
            }
        })
    };
    this.ToggleFavPlayer = function (PlayerID, userID, el, onImage, offImage)
    {
        _el = $(el);
        _onImage = onImage;
        _offImage = offImage;

        $.ajax({
            type: "POST",
            url: "/ws/ws.asmx/ToggleFav",
            data: "{'objType':'player','objID':'" + PlayerID + "','PlayerID':'" + userID + "'  }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg)
            {
                toggleTickbox(msg.d);
            }
        })
    };

    var toggleTickbox = function (state)
    {
        if (_el != null)
        {
            if (state)
            {
                _el.attr("src", _onImage);
            }
            else
            {
                _el.attr("src", _offImage);
            }
        }
    };

};

///Init tooltip offset fix for popups
/// it will display the tooltip to the left ot to the right
/// based on its position relatively to parent
var Tooltip = new function ()
{
    this.Init = function ()
    {
        $(document).ready(function ()
        {
            $("a.tooltip").hover(function ()
            {
                var _tooltip = $(this);
                if (!_tooltip.data("set"))
                {

                    var _parentWidth = _tooltip.offsetParent().width();
                    var _tooltipLeft = _tooltip.position().left;
                    var _span = _tooltip.children("span");
                    
                    if (_tooltipLeft < (_parentWidth / 2))
                    {

                        _span.css("right", "auto");
                        _span.css("left", "18px");

                    }
                    else
                    {
                        _span.css("right", "18px");
                        _span.css("left", "auto");
                    }
                    _tooltip.data("set", true);
                    
                }

            });
        });

    }
}
