function $(id)
{
    return document.getElementById(id);
}

function getCssStyle(elem, attr) {
    var cssValue;
    elem = $(elem);
    if (elem.currentStyle){
        cssValue = elem.currentStyle[attr];
    }else{
        cssValue = window.getComputedStyle(elem, null)[attr];
    }
    return cssValue;
}

function sbmt() {
    document.loginform.submit();

}

function setAutoCalc() {
    //document.ticketform.autocalc.value = "yes";
    //document.ticketform.submit();
}

function hideRecalculate() {
    /*
    var x = $('right_img_recalculate');
    var y = $('button_img_recalculate');
    var z = $('left_img_recalculate');

    x.style.display = 'none';
    y.style.display = 'none';
    z.style.display = 'none'; */
}

function getSiteName() {
    // for example, returns "triobet" for www.triobet.com
    hostparts = location.hostname.split('.');
    if (hostparts[0] == 'www') return hostparts[1];
    else return hostparts[0];
}

function refreshToSelections() {
    window.parent.selection.location = 'selection';
}

function showTime(time) {
    try {
    t = $('time');
    if (t) {t.innerHTML = time;}
    }
    catch(e) {}
}

function autoPost() {
    window.open('', 'target', 'height=580, width=800, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, status=no');
    form = $('windowForm');
    form.target='target';
    form.submit();
    pathname = document.location.pathname;
    document.location.pathname = pathname;
}

function trackPage(url) {
    try {
        pageTracker._trackPageview(url);
    } catch(e) {}
}

function openFlashPoker() {
    trackPage('/play-poker-in-browser');
    var poker_link = 'https://mppv2flash3.valueactive.eu/' + getSiteName() + '/index.aspx';
    openFlashPokerPopup('poker_lobby', poker_link, 790, 571)
}

function openFlashPokerPopup(name, url, width, height) {
    var new_win = window.open(url, name,
                              'width=' + width + ',height=' + height + ',directories=no,toolbar=no,resizable=no,location=no,menubar=no,status=no,scrollbars=no');
}

function getHttpRequest() {
    var request = false;
        try {
            request = new XMLHttpRequest();
        } catch (trymicrosoft) {
            try {
                request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (othermicrosoft) {
                try {
                    request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (failed) {
                    request = false;
            }
        }
    }
    if (!request)
        alert("Failed in initializing XMLHttpRequest!");
    return request;
}

function checkPokerTrans(lang, msg) {
    request = getHttpRequest();
    url = "/" + lang + "/poker_trans?cmd=display_box";
    if (msg !=null)
        url += "&msg=" + msg
    request.open("GET", url, true);
    request.onreadystatechange = displayPokerTrans;
    request.send(null);
}

function displayPokerTrans() {
    try {
        if (request.readyState == 4)
            if (request.status == 200) {
                response = request.responseText;
                $("transfer-box").innerHTML = response;
            }
    } catch (error) {
    }
}

function submitFormById(id){
    form = $(id);
    if (form){
        form.submit();
    }
}

function forceFrame(force_url) {
    // do not forceFrame if we're running selenium tests
    // This code will cause error message for ticket frame in livebet page with domain changing by minigame including, so catch the error.
    // And I think we should remove this hacky code which only for test.
    try {
        if (top.location.pathname.substring(1,9) == 'selenium')
            return
    } catch (e) {}

    if (top == window)
        top.location.href = force_url;
}

function setTopDomain(domain) {
/* Use for top window to set domain */
    document.domain = domain;
}

function setFrameDomain(domain) {
/* Use for iframe, to solve the crossdomain problem for communication in different frames.
 * If top window's domain has been set, set it in iframe as well.
 * Else use the default domain.
 *
 * This function should be called in iframe.
 */

    try {
        // if top window's domain has been set, it will encounter an error here when try to visit top.document.domain
        top.document.domain;
    } catch(e) {
        document.domain = domain;
    }
}

function getOddsClass(odds_style, selected_odds_style) {
    if (selected_odds_style == odds_style) {
        return "display_block";
    } else {
        return "display_hidden";
    }
}

function getOldOddsClass(odds) {
    if (odds.getAttribute("class") != undefined) {
        return odds.getAttribute("class");
    } else if (odds.className != undefined) {
        return odds.className;
    }
}

function setOddsClass(odds_style, selected_odds_style, odds) {
    var className = getOddsClass(odds_style, selected_odds_style);
    if (className != getOldOddsClass(odds)) {
        odds.setAttribute("class", className);
        odds.setAttribute("className", className);
    }
}

function onOddsStyleChange(odds_style) {
    var odds_list = document.getElementsByTagName("span");
    var odds_len = odds_list.length;
    for (var i=0; i< odds_len; i++) {
        var odds = odds_list[i];
        var id = odds.id;
        if (id == undefined) {
            continue;
        }
        if (id.indexOf("odds_decimal") == 0) {
            setOddsClass(1, odds_style, odds);
        } else if (id.indexOf("odds_us") == 0) {
            setOddsClass(2, odds_style, odds);
        } else if (id.indexOf("odds_fractional") == 0) {
            setOddsClass(3, odds_style, odds);
        }
    }
}

function onHeaderOddsStyleChange(odds_style) {
    if(use_ajax_selection) {
        showProgress();
        setTimeout("oddsStyleChangedInAjax(\""+odds_style+"\")", loadingDelay);
    } else {
        onOddsStyleChange(odds_style);
        left.onOddsStyleChange(odds_style);
        submitOddsStyleChange(odds_style);
    }
}

function submitOddsStyleChange(odds_style) {
    request = getHttpRequest();
    url = "/selection?odds_style=" + odds_style ;
    request.open("POST", url, false);
    request.send(null);
}

function refreshSelectionByOddsStyle(){
    var request = getHttpRequest();
    request.onreadystatechange = function() {
        if(request.readyState == 4) {
            var resp = "";
            if(request.status == 200)
                resp = request.responseText;
            else {
                showAjaxMessage("Sorry, we can't get any information now. Please try it later.");
                return;
            }
            if (resp != "") {
                var odds_style = resp;
                var old_odds_style = $("old_odds_style").value;
                if (odds_style != old_odds_style) {
                    onOddsStyleChange(odds_style);
                    left.onOddsStyleChange(odds_style);
                    $("odds_style").value = odds_style;
                }
            }

        }
    }
    var url = "/selection?cmd=get_odds_style";
    request.open("GET", url, true);
    request.send(null);

}

function findElement(parent, tagName, idRE)
{
    var elements = parent.getElementsByTagName(tagName);
    for(var i = 0; i < elements.length; i++)
    {
        if(elements[i].id != undefined && elements[i].id.match(idRE))
        {
            return elements[i];
        }
    }
    return undefined;
}

function popupWindow(url, name, features){
    // set default features values
    var width = 300;
    var height = 200;

    var extraParams = {'width': width,
                       'height': height,
                       'directories': 'no',
                       'location': 'no',
                       'menubar': 'no',
                       'resizable': 'yes',
                       'status': 'no',
                       'toolbar': 'no'}

    // override the default features values.
    if (features != undefined) {
        if (typeof(features) != "object") {
            // convert json string to be dictionary obj
            features = eval('('+features+')')
        }
        for (_feature in features) {
            extraParams[_feature] = features[_feature]
        }
    }

    var needScrollBars='no';
    if (extraParams['left'] == undefined) {
        var left = (screen.width - extraParams['width'] )/2;
        if(left < 0){left = 0; needScrollBars='yes';}
        extraParams['left'] = left;
    }

    if (extraParams['top'] == undefined) {
        var top = (screen.height - extraParams['height'] )/2;
        if(top < 0){top = 0; needScrollBars='yes';}
        extraParams['top'] = top;
    }

    if (extraParams['scrollbars'] == undefined) {
        extraParams['scrollbars'] = needScrollBars;
    }

    // convert the feature dic into string
    var params = "";
    for (_param in extraParams) {
        if (params != "") {
            params += ', '+_param+'='+extraParams[_param];
        }
        else {
            params += _param+'='+extraParams[_param];
        }
    }

    window.open(url, name, params).focus();
    return false;
}

/**
 *
 * @param id
 * @param displayValue - Sometimes not the 'block' style is the needed.
 * @return
 */
function showById(id, displayValue) {
    if (displayValue == undefined) {
        displayValue = 'block';
    }
    $(id).style.display = displayValue;
}

function hideById(id) {
    $(id).style.display = 'none';
}

function isHidden(id) {
    return $(id).style.display == 'none';
}


function clearForm(formName) {
    var formObj = $(formName);
    var formElements = formObj.elements;
    // Traversal of all elements in the form, set initial value for them.
    for (var i=0; i<formElements.length; i++) {
        var element = formElements[i];
        switch (element.type) {
            case 'text':
            case 'password':
            case 'textarea':
                element.value = '';
                break;
            case 'radio':
            case 'checkbox':
                element.checked = false;
                break;
            case 'select-multiple':
                element.selectedIndex = -1;
                break;
            case 'select-one':
               element.selectedIndex = 0;
                break;
            default:
                break;
        }
    }
}

function setSelected(selectElement, selectedValue) {
    // set the value selected for select input.
    for (var j=0; j<selectElement.options.length; j++) {
        if (selectElement.options[j].value == selectedValue) {
            selectElement.options[j].selected = true;
            break;
        }
    }
}

var global_visible_popups = [];

function hidePopups(){
    if (null != $('veil'))
        hideById("veil");
    while(global_visible_popups.length > 0)
    {
        hideById(global_visible_popups.pop());
    }
}

function showVeil() {
    var veil = $('veil');
    if (null == veil) return;
    if (typeof document.body.style.maxHeight == "undefined"){
        var width = Math.max(document.documentElement.clientWidth,
                document.documentElement.scrollWidth);
        var height = Math.max(document.documentElement.clientHeight,
                document.documentElement.scrollHeight);
        veil.style.width = width + "px";
        veil.style.height = height + "px";
    }
    showById('veil');
}

function hideIE6SelectControl(popup) {
    // To fix an IE6 defect, in IE6 a div layer with bigger z-index will not
    // really cover a select control.
    // One flexible workaround is to create an iframe under the popup.
    if (typeof document.body.style.maxHeight != "undefined") return;
    // only for IE6, older
    var cover = $(popup.id + "_cover")

    if(!cover)
    {
        cover=document.createElement("DIV");
        cover.style.display="none";
        cover.style.position="absolute";
        cover.style.backgroundColor="white";
        cover.style.width=popup.clientWidth;
        cover.style.height=popup.clientHeight;
        var L=document.createElement("IFRAME");
        L.src="/common/empty.htm";   // to avoid security warning when load
                                     // unsecured page from secured page
        L.name="completionFrame";
        L.width=cover.style.width;
        L.height=cover.style.height;
        cover.appendChild(L);
        document.body.appendChild(cover);
        cover.id = popup.id + "_cover"
    }
    cover.style.left=popup.style.left;
    cover.style.top=popup.style.top;
    cover.style.display = "block";

    global_visible_popups.push(cover.id);
}

function getDefaultErrorMessage() {
    return "Sorry, we can't get any information now. Please try it later.";
}

function showCentralizedPopup(popup) {
    showVeil();
    global_visible_popups.push(popup.id);
    popup.style.display = 'block';
    var offsettop = (document.documentElement.clientHeight - popup.clientHeight) / 2 + document.documentElement.scrollTop;
    var offsetleft = (document.body.clientWidth - popup.clientWidth) / 2;
    if(offsettop < 0) {offsettop = 0}
    if(offsetleft < 0) {offsetleft = 0}
    popup.style.top = offsettop + "px";
    popup.style.left = offsetleft + "px";
    popup.style.position = "absolute";
    hideIE6SelectControl(popup); // to fix IE6 select control defect.
}

function openCasinoFullscreen(url) {
    var newwin = window.open(url, "_blank", "menubar=0,toolbar=0,location=0,directories=0,status=1,left=0,top=0,width="+screen.width+",height="+screen.height+",scrollbars=0");
    newwin.focus();
    parent.document.location.href='/casino';
}

function toggleBlog(id, img_id, site_id) {
    var widget = $(id);
    var img_obj = $(img_id);
    if (widget.style.display == "none") {
        widget.style.display = "block";
        img_obj.src = site_id + "/images/blog_arrow_down.gif";
    } else {
        widget.style.display = "none";
        img_obj.src = site_id + "/images/blog_arrow_right.gif";
    }
}

/***********************************************
* IFrame SSI script II- © Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
* Visit DynamicDrive.com for hundreds of original DHTML scripts
* This notice must stay intact for legal use
***********************************************/

//Input the IDs of the IFRAMES you wish to dynamically resize to match its content height:
//Separate each ID with a comma. Examples: ["myframe1", "myframe2"] or ["myframe"] or [] for none:
var iframeids=["ticketIFrame"]

//Should script hide iframe from browsers that don't support this script (non IE5+/NS6+ browsers. Recommended):
var iframehide="yes"

var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1]
var FFextraHeight=parseFloat(getFFVersion)>=0.1? 5 : 0 //extra height in px to add to iframe in FireFox 1.0+ browsers

function resizeCaller() {
var dyniframe=new Array()
for (i=0; i<iframeids.length; i++){
if ($)
resizeIframe(iframeids[i])
//reveal iframe for lower end browsers? (see var above):
if ((document.all || $) && iframehide=="no"){
var tempobj=document.all? document.all[iframeids[i]] : $(iframeids[i])
tempobj.style.display="block"
}
}
}

/**
 * Resizes the frame object to the content it has. It was needed to refactor
 * this logic out from resizeIframe to be able to resize an IFrame inside the
 * IFrame itself.
 *
 * On Firefox, the addEventListeners parameter was needed, as when calling
 * this method from inside the Iframe, where we only have an Ajax-refresh
 * it is not needed to add the onLoad event listener again - on top of it, it
 * causes a JavaScript error. Unfortunately, we can not get the list of event
 * handlers, and calling removeEventListener does not help also. I assume, that
 * detachEvent+attachEvent has the similar functionality.
 *
 * @param currentfr - The IFrame object to resize.
 * @param addEventListeners - Whether to add the event listener to onLoad or not.
 * @return - void
 *
 * @see ticket_handler.js
 */
function resizeIframeObject(currentfr, addEventListeners) {

if (currentfr && !window.opera){
    currentfr.style.display="block";
    if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) //ns6 syntax
        currentfr.height = currentfr.contentDocument.body.offsetHeight+FFextraHeight+5;
    else if (currentfr.Document && currentfr.Document.body.scrollHeight) //ie5+ syntax
        currentfr.height = currentfr.Document.body.scrollHeight+20;
    else if (currentfr.Document && currentfr.Document.documentElement.scrollHeight) //ie8 syntax
        currentfr.height = currentfr.Document.documentElement.scrollHeight+5;
    //When calling from inside an IFrame, do not add the event listeners again
    if (addEventListeners) {
        if (currentfr.addEventListener) {
            currentfr.addEventListener("load", readjustIframe, false);
        }
        else if (currentfr.attachEvent) {
            currentfr.detachEvent("onload", readjustIframe) // Bug fix line
            currentfr.attachEvent("onload", readjustIframe)
        }
    }
}

}

/**
 * Helper method to resize an IFrame with a given id.
 *
 * Note: this method searches for the id inside the current document object,
 * be aware of this if you want to use it eg.: _inside_ and IFrame.
 *
 * @param frameid - Id of the IFrame to resize.
 * @return - void
 */
function resizeIframe(frameid) {
var currentfr=$(frameid);
//We must be backward compatible, this method added the event listeners previously
resizeIframeObject(currentfr, true);
}


function readjustIframe(loadevt) {
var crossevt=(window.event)? event : loadevt
var iframeroot=(crossevt.currentTarget)? crossevt.currentTarget : crossevt.srcElement
if (iframeroot) {
    resizeIframe(iframeroot.id);
}
}

function loadintoIframe(iframeid, url){
if ($)
$(iframeid).src=url
}

if (window.addEventListener)
window.addEventListener("load", resizeCaller, false)
else if (window.attachEvent)
window.attachEvent("onload", resizeCaller)
else
window.onload=resizeCaller

function adjustHeight(min_height) {
    var height = document.documentElement.clientHeight;
    var mainheight = height - $("framecontentTop").clientHeight - $("framecontentBottom").clientHeight;
    var livescoreheight = mainheight > min_height ? mainheight : min_height;
    var livescore = $("livescore");
    livescore.style.height = livescoreheight + "px";
}

function focus_element(element) {
    if (typeof(element) == "object") {
        element.focus();
    }
}

function refreshDocumentWithFilter(filter_name, filter_value){
    var currentHref = document.location.href;
    if (currentHref.indexOf('?') > -1) {
        var r = new RegExp("("+filter_name+"\=)(.*?)($|\&)", "g");
        if (r.test(currentHref)) {
            currentHref = currentHref.replace(r, "$1"+filter_value+"$3");
        } else {
            currentHref = currentHref + "&" + filter_name + "=" + filter_value;
        }
    } else {
        currentHref = currentHref + "?" + filter_name + "=" + filter_value;
    }
    hideProgress();
    document.location.href = currentHref;
    return false;
}

function oddsStyleChangedInAjax(odds_style) {
    var request = getHttpRequest();
    var url = "/selection?odds_style=" + odds_style;
    request.onreadystatechange = function() {
        if(request.readyState == 4) {
            if(request.status == 200) {
                refreshDocumentWithFilter("odds_style", odds_style);
            } else {
                showAjaxMessage("Sorry, we can't get any information now. Please try it later.");
                return;
            }
        }
    }
    request.open("POST", url, true);
    request.send(null);
}

String.prototype.strip = function() { return this.replace(/(^\s*)|(\s*$)/g, ""); }

document.getElementsByClassAndTagName = function(clsName, tag) {
    var retVal = new Array();
    if (!tag) { tag = "*"; }
    var elements = document.getElementsByTagName(tag);
    for (var i = 0; i < elements.length; i++) {
        var classes = elements[i].className.split(" ");
        for (var j = 0; j < classes.length; j++) {
            if (classes[j] == clsName) {
                retVal.push(elements[i]);
            }
        }
    }
    return retVal;
}

function openGame(url, popup, width, height) {
    if (popup)
        window.open(url, '',
            'width=' + width + ', height=' + height + ', scrollbars=yes');
    else
        window.location = url;
}

function loginFocus(item, value) {
    var userName = $('userName');
    var password = $('password');
    if (item.value == value) {
        userName.value = '';
        password.value = '';
    }
}

function loginBlur(item, userNameValue, passwordValue) {
    var userName = $('userName');
    var password = $('password');
    if (item.value == '') {
        userName.value = userNameValue;
        password.value = passwordValue;
    }
}

function refreshBettingNumber() {
    var betting_table = $('list');
    var betting_number = betting_table ? betting_table.getElementsByTagName('tr').length / 2 : 0;
    var betting_number_span = top.document.getElementById('betting_number');
    if (betting_number_span) {
        betting_number_span.innerHTML = betting_number;
    }
}
