// JavaScript Document
/*
	Developwe   : Jansan John
	E-Mail      : jans4u[at]gmail[dot]com
	Description : Core Javascript Functions
*/

/* 
############################################################################################################
--------------------------   DOM FUNCTIONS STARTS HERE  -------------------------- 
############################################################################################################
*/

/* -------------------------------------------------------------
// Return the id of the attribute. //
----------------------------------------------------------------- */
function $(id){return document.getElementById(id);}

/* -------------------------------------------------------------
// Return the value of the attribute.. //
----------------------------------------------------------------- */
function $V(id){return document.getElementById(id).value;}

/* -------------------------------------------------------------
// Return the array elements corressponding to the name of the attribute.//
----------------------------------------------------------------- */
function $N(name){return document.getElementsByName(name);}

/* -------------------------------------------------------------
// Return the value of the elements corressponding to the name of the attribute. //
----------------------------------------------------------------- */
function $NV(name)
{
	var elementsArray = document.getElementsByName(name);
	var elementsArraySize = elementsArray.length;
	var elementValues = new Array();
	
	for(var i=0; i<elementsArraySize; i++)
	{
		elementValues[i] = elementsArray[i].value;
		//elementValues.push(elementsArray[i].value);
	}
	return elementValues;
}

/* -------------------------------------------------------------
// get the text content of an object. //
----------------------------------------------------------------- */
function getTextContent(obj){
    if (obj.innerText) {
        return obj.innerText;
    } else if (obj.textContent) {
        return obj.textContent;
    } else {
        return obj.innerHTML;
    }
}

/* -------------------------------------------------------------
// set the text content of an object. //
----------------------------------------------------------------- */
function setTextContent(obj, text){
    if (obj.innerText) {
        obj.innerText = text;
    } else if (obj.textContent){
        obj.textContent =  text;
    } else {
        obj.innerHTML = text;
    }
}

/* -------------------------------------------------------------
// get all elements with the given class name //
----------------------------------------------------------------- */
function getElementsByClassName(elemClass,elem,tag) {
	var sourceElements = elem.getElementsByTagName(tag);
	var matchingElements = new Array();
	var matchingElementsIndex = 0;
	var pattern = new RegExp("(^|\\s)"+elemClass+"(\\s|$)");
	for (i = 0; i < sourceElements.length; i++) {
		if ( pattern.test(sourceElements[i].className) ) {
			matchingElements[matchingElementsIndex] = sourceElements[i];
			matchingElementsIndex++;
		}
	}
	return matchingElements;
}

function addEvent(elm, evType, fn, useCapture)
{
	if (elm==null){
		return null;
	}
	if (/safari/i.test(navigator.userAgent) && evType == 'dblclick') {
		elm['ondblclick'] = handler;
	} else if (elm.addEventListener){
		elm.addEventListener(evType, fn, useCapture);
		return true;
	} else if (elm.attachEvent){
		var r = elm.attachEvent('on'+evType, function(){ fn(new W3CDOM_Event(elm)) } );
		return r;
	} else {
		throw new UserException("Cannot add event listener");
	}
}


function W3CDOM_Event(currentTarget) {
	this.currentTarget  = currentTarget;
	this.preventDefault = function() { window.event.returnValue = false }
	return this;
}

function UserException(message) {
   this.message = message;
   this.name = "UserException";
}


function classExists(obj, className){
	return new RegExp('\\b'+className+'\\b').test(obj.className);
}

function removeClass(obj,className){

	var rep=obj.className.match(' '+className)?' '+className:className;
	obj.className=obj.className.replace(rep,'');
}

function addClass(obj,className){
	if(!classExists(obj,className)){
		obj.className+=' '+className;
	}
}

/* ----------------------------------------------------------------
// trim functions. add to native function using prototype
------------------------------------------------------------------ */
String.prototype.trim = function() {
   return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function() {
   return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function() {
   return this.replace(/\s+$/,"");
}

String.prototype.isempty = function(){
    return this.trim().length == 0;
}

Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
}
/* ----------------------------------------------------------------
// calculate the current window width //
------------------------------------------------------------------ */
function pageWidth() {
  return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}

/* ----------------------------------------------------------------
// calculate the current window height //
------------------------------------------------------------------ */
function pageHeight() {
  return window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
}

/* ----------------------------------------------------------------
// calculate the current window vertical offset //
------------------------------------------------------------------ */
function topPosition() {
  return typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}

/* ----------------------------------------------------------------
// calculate the position starting at the left of the window //
------------------------------------------------------------------ */
function leftPosition() {
  return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}

/* -------------------------------------------------------------------------------------------------------------
// xGetEleAtPoint, Copyright 2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
/*
Parameters :x  integer
           :y  integer
Return     : Returns an element reference, or null if no element is at the given point.
------------------------------------------------------------------------------------------------------------------ */
function xGetEleAtPoint(x, y)
{
  var he = null, z, hz = 0;
  var i, list = xGetElementsByTagName('*');
  for (i = 0; i < list.length; ++i) {
    if (xHasPoint(list[i], x, y)) {
      z = xZIndex(list[i]);
      z = z || 0;
      if (z >= hz) {
        hz = z;
        he = list[i];
      } 
    }
  }
  return he;
}

/* ----------------------------------------------------------------
// return X and Y co-ordinate of an element //
------------------------------------------------------------------ */
function getXY(obj) {
    var objX = 0;
    var objY = 0;    
    if(obj.offsetParent) {
        while(obj.offsetParent) {
            objX = objX + obj.offsetLeft;
            objY = objY + obj.offsetTop;
            obj = obj.offsetParent;
        }
    }
    return [objX,objY];
}

/* ----------------------------------------------------------------
// move an element to X Y position //
------------------------------------------------------------------ */
function moveObj(obj,x,y) {
    obj.style.top = y+"px";
    obj.style.left = x+"px";
    return true;
}

/* ----------------------------------------------------------------
//Resizes page based on the size of an element in the page
------------------------------------------------------------------ */
function resizePage(elementID) {

  if (typeof elementID == "undefined")
    var element = document.body;
  else
    var element = document.getElementById(elementID);
  
  var oH = element.clip ? element.clip.height : element.offsetHeight;
  var oW = element.clip ? element.clip.width : element.offsetWidth;
  
  document.body.style.overflow = 'hidden';
  
  window.resizeTo( oW + 0, oH + 0 );
  var myW = 0, myH = 0, d = window.document.documentElement, b = window.document.body;
  
  if (window.innerWidth) { 
    
    myW = window.innerWidth; 
    myH = window.innerHeight; 
  }
  else if (d && d.clientWidth) { 
  alert(d.clientHeight);
    
    myH = d.clientHeight; 
  }
  else if (b && b.clientWidth) { 
    
    myW = b.clientWidth; 
    myH = b.clientHeight;
  }
  
  if (window.opera && !document.childNodes)
    myW += 16;
  
  document.body.style.overflow = '';
  window.resizeTo( oW + ((oW + 0) - myW), oH + ((oH + 0) - myH) );
  if( window.focus ) {window.focus();}
}

/* ----------------------------------------------------------------
//check option items are exist in select beob
------------------------------------------------------------------ */
function hasOptions(obj) {
	if (obj!=null && obj.options!=null) { return true; }
	return false;
}
/* ----------------------------------------------------------------
//return selected multi selct box items.
------------------------------------------------------------------ */
function getMultipleSelectionItems(elementId,array){ 
	var selected = new Array(); 
	var mySelect = document.getElementById(elementId);
	var mySelectLength 	= mySelect.length;
	for(var i = 0; i < mySelectLength; i++) { 
		if(mySelect.options[i].selected) { 
			selected.push(mySelect.options[i].value); 
		} 
	} 
	if(array != 'true') return selected.toString(); else return selected; 
} 
/* ----------------------------------------------------------------
// select option item based on value.
------------------------------------------------------------------ */
function selectOptionItem(elementId, elementValue) {
	var elem = document.getElementById(elementId);
	var elemLength = elem.length;
	for(var i = 0; i < elemLength; i++) {	
		if(elem.options[i].value == elementValue) {
			elem.selectedIndex = i;
		}
	}
} 
/* ----------------------------------------------------------------
// select option item based on value.
------------------------------------------------------------------ */
function keyDownHappen(e) {
	if(!e) var e = window.event;
	e.stopPropogation=true;
	return false;
}














/* 
############################################################################################################
--------------------------   AJAX FUNCTIONS STARTS HERE  -------------------------- 
############################################################################################################
*/

/* -------------------------------------------------------------
// Return the xmlHttpObject. //
----------------------------------------------------------------- */
function GetXmlHttpObject(handler)
{ 
	var objXmlHttp=null
	if (navigator.userAgent.indexOf("Opera")>=0)
	{
		//alert("Opera Is Not Supporting. Use Some Other Browsers") 
		//return
		objXmlHttp=new XMLHttpRequest();
		objXmlHttp.onload=handler;
		objXmlHttp.onerror=handler;
		return objXmlHttp;
	}
	if (navigator.userAgent.indexOf("MSIE")>=0)
	{ 
		var strName="Msxml2.XMLHTTP";
		if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
		{
			strName="Microsoft.XMLHTTP";
		} 
		try
		{ 
			objXmlHttp=new ActiveXObject(strName);
			objXmlHttp.onreadystatechange=handler; 
			return objXmlHttp;
		} 
		catch(e)
		{ 
			alert("Error. Scripting for ActiveX might be disabled"); 
			return; 
		} 
	} 
	if (navigator.userAgent.indexOf("Mozilla")>=0)
	{
		objXmlHttp=new XMLHttpRequest();
		objXmlHttp.onload=handler;
		objXmlHttp.onerror=handler; 
		return objXmlHttp;
	}
}

/* -------------------------------------------------------------
Send an ajax request to the url mentioned
URL 	   : SERVER SIDE SCRIPT NAME
PARAMETERS : URL parameters
callback   : callback function
requesttype: POST OR GET
async      : asycronous or synchronous, TRUE or FALSE
---------------------------------------------------------------- */
function makeRequest(url,parameters,callback,requesttype,async)
{
	
	if(requesttype=='POST')
	{
		xmlHttp=GetXmlHttpObject(callback) 
		xmlHttp.open("POST",url,async);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		xmlHttp.send(parameters);
	}else if(requesttype=="GET")
	{
		url    = url+'?'+parameters;
		xmlHttp=GetXmlHttpObject(callback) 
		xmlHttp.open("GET", url , async) 
		xmlHttp.send(null) 
	}
}

















/* 
############################################################################################################
--------------------------   DATA MANIPULATION FUNCTIONS STARTS HERE  -------------------------- 
############################################################################################################
*/

/* -------------------------------------------------------------
// function for sanitizing tha data
----------------------------------------------------------------- */
function sanitizeString(resText)
{
	var response = resText.replace(/\n/g, "<br/>");
    response     = response.replace(/\r/g, "\\r");	
	return response;
}

/* ----------------------------------------------------------------
// convert form elements to a querystring//
------------------------------------------------------------------ */
function serialiseForm(form) {
  var strArr = form.elements.length > 0 ? "?" : "";
  for(i=0; i < form.elements.length; i++) {
    strArr += form.elements[i].name + '=' + form.elements[i].value;
    strArr += (i+1) < form.elements.length ? "&" : "";
  }
  return strArr;
}















/* 
############################################################################################################
--------------------------   DATE TIME MANIPULATION FUNCTIONS STARTS HERE  -------------------------- 
############################################################################################################
*/

/* ----------------------------------------------------------------
// get day name corresponding to a day number  //
------------------------------------------------------------------ */
function getDayName(intDay){
    var DayArray = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
    return DayArray[intDay];
}

/* ----------------------------------------------------------------
// get month name corresponding to a month number //
------------------------------------------------------------------ */
function getMonthName(intMonth){
    var MonthArray = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    return MonthArray[intMonth];    
}

/* ----------------------------------------------------------------
// get current date string //
------------------------------------------------------------------ */
function getDateStrWithDOW(){
    var today = new Date();
    var year = today.getYear();
    if(year<1000) year+=1900;
    return getDayName(today.getDay()) + ", " + today.getDate() + " " + getMonthName(today.getMonth()) + " " + year;
}















/* 
############################################################################################################
--------------------------   COOKIE FUNCTIONS STARTS HERE  -------------------------- 
############################################################################################################
*/
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

function getFullCookie(){
// to access the string held in the named cookie
    var tCookie = unescape(document.cookie);
    // sName will be populated by javascript variable set using TCL
    if (document.cookie.length > 0) {          
        nBegin = tCookie.indexOf(sName+'=');

        if (nBegin != -1) {           
            nBegin += sName.length+1;       
            nEnd = tCookie.indexOf(";", nBegin);
            if (nEnd == -1) nEnd = tCookie.length;
            return tCookie.substring(nBegin, nEnd);
        } 
    }
    return "";
}

function showAllCookies () {
    alert("Cookies: "+ unescape(document.cookie));
}


















/* 
############################################################################################################
--------------------------   UTILLITY FUNCTIONS STARTS HERE  -------------------------- 
############################################################################################################
*/
function getBrowser() {
        var agt=navigator.userAgent.toLowerCase();
        if ((navigator.platform == "MacPPC" || navigator.platform == "mac") && agt.indexOf("aol") != -1) return 'aolmac';
        if (agt.indexOf("opera") != -1) return 'opera';
        if (agt.indexOf("staroffice") != -1) return 'staroffice';
        if (agt.indexOf("webtv") != -1) return 'webtv';
        if (agt.indexOf("beonex") != -1) return 'beonex';
        if (agt.indexOf("chimera") != -1) return 'chimera';
        if (agt.indexOf("netpositive") != -1) return 'netpositive';
        if (agt.indexOf("phoenix") != -1) return 'phoenix';
        if (agt.indexOf("firefox") != -1) return 'firefox';
        if (agt.indexOf("safari") != -1) return 'safari';
        if (agt.indexOf("skipstone") != -1) return 'skipstone';
        if (agt.indexOf("msie") != -1) return 'internetexplorer';
        if (agt.indexOf("netscape") != -1) return 'netscape';
        if (agt.indexOf("mozilla/5.0") != -1) return 'mozilla';
        if (agt.indexOf('\/') != -1) {
        if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
        return navigator.userAgent.substr(0,agt.indexOf('\/'));}
        else return 'Netscape';} else if (agt.indexOf(' ') != -1)
        return navigator.userAgent.substr(0,agt.indexOf(' '));
        else return navigator.userAgent;
}

/* ----------------------------------------------------------------
// mailToFriend //
------------------------------------------------------------------ */
function mailToFriend(sSubject,sBody) {
    var linkURL = window.location.href;
    var bodyText = escape(sBody + linkURL);
    var subject = escape(sSubject);
    var mailto = 'mailto:?subject='+subject+'&body='+bodyText;
    window.location.href = mailto;
}

/* ----------------------------------------------------------------
// BookMark Link //
------------------------------------------------------------------ */
function CreateBookmarkLink (title,url) {
    if (window.sidebar) {// firefox
        window.sidebar.addPanel(title, url, "");
    } else if(window.opera && window.print) { // opera
        var elem = document.createElement('a');
        elem.setAttribute('href',url);
        elem.setAttribute('title',title);
        elem.setAttribute('rel','sidebar');
        elem.click();
    } else if(document.all) {// ie
        window.external.AddFavorite(url, title);
    }
}
/* ----------------------------------------------------------------
// get a randome number //
------------------------------------------------------------------ */
function getRand()
{
    var oDate = new Date();
    return( "" + oDate.getHours() + oDate.getMinutes() + oDate.getSeconds() + oDate.getMilliseconds() + ( Math.random() * ( 1 + Math.random() ) ) ).replace( /\./g, "" );
}

/* ----------------------------------------------------------------
// toggle display of elements //
------------------------------------------------------------------ */
function toggleVisibility(elementReference) {
	var e = elementReference;
	if(!e || typeof e != "object") return;
	e.style.display = (e.style.display==='none') ? 'block' : 'none';
}

/* ----------------------------------------------------------------
// UCFirst (upper case first letter) //
------------------------------------------------------------------ */
function UCFirst(str){
   // split string
   firstChar = str.substring(0,1);
   remainChar = str.substring(1);

   // convert case
   firstChar = firstChar.toUpperCase(); 
   remainChar = remainChar.toLowerCase();

   return firstChar + remainChar

}

/* ----------------------------------------------------------------
// UCWords (upper case the first character of each word in a string) //
------------------------------------------------------------------ */
function UCWords(str) {
	var doneStr = '';
	var len = str.length;
	var wordIdx = 0;
	var char;
	for (var i = 0;i < len;i++) {
		char = str.substring(i,i + 1);
		if (' -/#$&'.indexOf(char) > -1) {
			wordIdx = -1;
		}
		if (wordIdx == 0) {
			char = char.toUpperCase();
		} else if (wordIdx > 0) {
			char = char.toLowerCase();
		}
		doneStr += char;
		wordIdx++;
	}
	return doneStr;
}











/* 
############################################################################################################
--------------------------   DYNAMIC IFRAME HEIGHT WITH DIV  -------------------------- 
############################################################################################################
*/
/*  loads url in iframe, transfers body content into div
    provides defaults for iframe and display div ID's 
    also supports use with multiple iframes and divs
    optional message for loading in display div 
    supports functions to be called once the div has been populated with new content 
    function in iframed document can be invoked should some operations need to be performed from there 
*/

function dw_loadExternal(url, ifrmId, divId, bLoadMsg,bLoadMsgType) {
    
	var loadingMsg ="";
	if(bLoadMsgType==1){
		loadingMsg = "Loading data. Please wait ...";
	}else{
		loadingMsg = "Retrieving Data - We are searching our database of 3000+  clubs to find your club fixtures and results. <br/>Please wait ...";
	}
	
	
	
	// defaults for iframe, display div
    ifrmId = ifrmId || 'buffer'; divId = divId || 'display'; 
    if ( window.frames[ifrmId] ) {
        // Could use location.replace method if you do not want back button to load previous iframe url 
        //window.frames[ifrmId].location.replace(url);
        window.frames[ifrmId].location = url;
        var lyr = document.getElementById? document.getElementById(divId): null;
        if ( lyr && bLoadMsg ) { // Option to display message while retrieving data 
            lyr.innerHTML = '<div class="loadingMsg"><br/><img src="'+httpReferer+'images/loading-data.gif" height="10px;" width="135px;"><br/><br/>&nbsp;'+loadingMsg+'</div>';
            lyr.style.display = 'block'; 
        }
        return false;
    } 
    return true; // other browsers follow link
}


// called onload of iframe 
// displays body content of iframed doc in div
// checks for and invokes optional functions in both current document and iframed document 
function dw_displayExternal(ifrmId, divId, fp) {
    // defaults for iframe, display div
    ifrmId = ifrmId || 'buffer'; divId = divId || 'display'; 
    
    var lyr = document.getElementById? document.getElementById(divId): null;
    if ( window.frames[ifrmId] && lyr ) {
        lyr.innerHTML = window.frames[ifrmId].document.body.innerHTML;
        lyr.style.display = 'block'; 

        // when using with script, may have some operations to coordinate
        // function in current doc or iframed doc (doOnIframedLoad)
        if ( typeof fp == 'function' ) {
            fp();			

        }
		
        // Demonstrated in tooltip demo
        if ( typeof window.frames[ifrmId].doOnIframedLoad == 'function' ) {
            window.frames[ifrmId].doOnIframedLoad();
        }
		       
		
    }
}












/* 
############################################################################################################
--------------------------   DEBUG FUNCTIONS STARTS HERE  -------------------------- 
############################################################################################################
*/


/* -------------------------------------------------------------------------------------------------------------
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
------------------------------------------------------------------------------------------------------------------ */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects
	 for(var item in arr) {
	  var value = arr[item];
	 
	  if(typeof(value) == 'object') { //If it is an array,
	   dumped_text += level_padding + "'" + item + "' ...\n";
	   dumped_text += dump(value,level+1);
	  } else {
	   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
	  }
	 }
	} else { //Stings/Chars/Numbers etc.
	 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
} 





