/**
 * GP global object
 */

//namespace
if (typeof GP == "undefined" || !GP) { 
    /**
     * GP namespace
     * @class GP
     */
    var GP = {}; 
}

Array.prototype.max = function(){
    return Math.max.apply(Math, this);
};
    
Array.prototype.min = function(){
    return Math.min.apply(Math, this);
};

//--------------------Shorthand methods-----------------------------------------------------

/*
 * Get element(s) by their id(s)
 * @param {String | HTMLElement | Array} el Accepts a string to use as an ID for getting a DOM reference, an actual DOM reference, or an Array of IDs and/or HTMLElements.
 * @return {HTMLElement | Array} A DOM reference to an HTML element or an array of HTMLElements.
 * @see YAHOO.util.Dom.get()
 */
GP.$  = function(el) {
    try{
        return YAHOO.util.Dom.get(el)
    }catch(e){}
    
    /** method get() from YAHOO.util.Dom */
    var get = function(el) {
		if (el && (el.nodeType || el.item)) { // Node or NodeList
            return el;
        }

        if ((typeof el === 'string') || !el) { // HTMLElement or null
            return document.getElementById(el);
        }

        if (el.length !== undefined) { // array-like 
            var c = [];
            for (var i = 0, len = el.length; i < len; ++i) {
                c[c.length] = get(el[i]);
            }
            return c;
        }
    };

    return get(el);
}

/**
 * Very simple logger :)
 */
if(!(GP.log)) GP.log = function(x) {};


//--------------------Common stuff----------------------------------------------------------

var isOpera = navigator.userAgent.indexOf('Opera') >= 0 || typeof window.opera != 'undefined';
var isMSIE = !isOpera && navigator.userAgent.indexOf('MSIE') != -1 && navigator.appName == "Microsoft Internet Explorer";

/* some layout fixes */
function fixLayout()
{
    if (isOpera) {
        var betslipDiv = document.getElementById('betslip_div');
        if (betslipDiv) {
            betslipDiv.style.marginBottom = '0px';
        }
    }
}

function roll (eThis, objHref) {
    var obj = document.getElementById(eThis);
    var objImg = objHref.getElementsByTagName('img')[0];
    var cookieVal, cookieName = eThis + '_enabled_state';
    if (obj.className == 'display') {
        obj.className = 'hide';
        objImg.src = '/s/img/i_roll_down.gif';
        cookieVal = 0;
    } else {
        obj.className = 'display';
        objImg.src = '/s/img/i_roll.gif';
        cookieVal = 1;
    }
    setCookie(cookieName, cookieVal, '/', 10);
}

function setCookie(c_name, value, path, expire_days)
{
	if(value===null) {
		deleteCookie(c_name, path, expire_days);
	}else{
	    var exdate = new Date();
	    exdate.setDate(exdate.getDate() + expire_days);
	    document.cookie = c_name + "=" + escape(value) + ((path) ? "; path=" + path : "") + ((expire_days == null) ? "" : ";expires=" + exdate);
	}
}

function getCookie(c_name)
{
    if (document.cookie && document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end=document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return null;
}

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

// @see https://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:indexOf
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}


if(!Array.push){
  Array.prototype.push = function(o){
  	this[this.length] = o;
  }
}


/** плюрализация */
function pluralForm($n, $form1, $form2, $form5) {
    if(!$form2) $form2=$form1;
    if(!$form5) $form5=$form1;

    if(Math.round($n)!=$n) return $form2; //2,5 рубля

    $n = Math.abs($n) % 100;
    if ($n > 10 && $n < 20) return $form5;
    var $n1 = $n % 10;
    if ($n1 > 1 && $n1 < 5) return $form2;
    if ($n1 == 1) return $form1;
    return $form5;
}

/** динамическое создание css селекторов*/
/** 
 * создает елемент style
 * @return Node
 */
function createStyleElement() {
	var style=document.createElement('style');
	style.setAttribute("type", "text/css");
	return style; 
}
/**
 * аппендит style в заголовок документа
 * @param Node style - ссылка на елемент style
 */
function appendStyleElement(style) {
	document.getElementsByTagName('head')[0].appendChild(style);
}
/**
 *  создает елемент style и аппендит его в заголовок
 *  @return Node
 */
function createAppendStyleElement(callback) {
	var style=createStyleElement();
	appendStyleElement(style);
	if(callback) callback(style);
	fixIEBug();
	return style; 
}
/**
 * добавляет селектор в елемент style
 * @param Node style - ссылка на елемент style
 * @param string selector - css selector
 * @param string  rules - css правила
 */
function addStyleSelector(style,selector,rules) {
	if(document.styleSheets && document.styleSheets.length && document.styleSheets[0].addRule) {// ie
		var styleSheet=document.styleSheets[document.styleSheets.length-1];
 		if(styleSheet.addRule) { // ie
        	selector=selector.split(',');
        	var s=selector.length;
        	while(s--) { 
        		styleSheet.addRule(selector[s],rules);
        	}
      	}
	} else {// w3c
		var cssText = document.createTextNode(selector+' {'+rules+'}');
		style.appendChild(cssText);
	}
}
/**
 * удаляет елемент style из документа
 * @param Node style - ссылка на елемент style
 */
function removeStyleElement(style) {
	document.getElementsByTagName('head')[0].removeChild(style);
	fixIEBug();
}
function fixIEBug() {
	var body=document.getElementsByTagName('body')[0];
	body.style.position='relative';
	body.style.position='static';
}

/**
 * аналог trim в php
 * @param string s
 * @return string
 */
var trim=function(s) {
	return s.replace(/(^\s+)|(\s+$)/g, "");	
};

/**
 * Расставили cellspacing="1" всем таблицам c классом simple (с использованием
 * пакета YUI DOM)
 *
 * @param void
 * @return void
 */
var addCellSpacing = function()
{
    var $D = YAHOO.util.Dom;
	var className = 'simple';
    var tables = document.getElementsByTagName('TABLE');

    for (var i = 0, t = tables.length; i < t; i++) {
		var currTable = tables[i];

		if ($D.hasClass(currTable, className)) {
			currTable.cellSpacing = '1';
		}
    }
};

/**
 * Меняет ссылку на статистику с /game123/ на /#url=game123/
 * @param Node a
 */
var changeStatLink=function(a) {
	var regEx=/\/r\/s\/((stage|game)[0-9]+)\/$/;
	var match=a.href.match(regEx);
	if(match && match[1]) a.href=['http://stat.golpas.com/stat/#url=',match[1],'/'].join('');
};

/**
 * добавляет событие онклик для смены ссылки на стату
 * @param string containerId
 */
var initChangeStatLink=function(containerId) {
	try {
		if(GP && !GP.mobile) {
			var $E = YAHOO.util.Event;
			if(containerId) $E.addListener(containerId,'click',function(e) {
				var i=0;
				for (var node = $E.getTarget(e); node; node = node.parentNode) {
					if(node.nodeName=='A') {
						changeStatLink(node);
						break;
					}
					if(i>3) break;
					i++;
				}
			});
		}
	} catch (e) {
		GP.log(e);
	}
}