var popups = new Array();
var nPopups = 0;
var ajaxStatus = new Array();
var popupData = new Array();
var intervals = new Array();
var formError = {fields:[],submit:null,counter:5,timeout:100,timer:null};

function _text(msg)
{
    if (lang[msg]!=undefined)
        msg = lang[msg];
    return(msg);
};

function showPopup(title,contents,properties)
{
    var id = nPopups++;
    var pElm = new Element('div',{'id':'p_'+id,'class':'popup-obj','style':'visibility: hidden'});
    popups[id] = [pElm,contents];
    var pBG = new Element('div',{id:'pbg'+id,'class':'popup-bg','style':'z-index: '+((id+1)*100)});
    pElm.appendChild(pBG);
    var pCnt = new Element('div',{id:'pc'+id,'class':'popup-container','style':'z-index: '+((id+1)*110)});
    pElm.appendChild(pCnt);
    var w = (properties.w||null)?properties.w+'px':'auto';
    var h = (properties.h||null)?properties.h+'px':'auto';
    pCnt.innerHTML = '<table class="popup-outer-table"><tr><td align="center" valign="middle">'+
                     '<table id="ptbl'+id+'" class="popup-inner-table">'+
                     '<tr><th class="pit-header"><div class="popup-close-btn" id="pcls'+id+'" onclick="closePopup('+id+')" title="'+_text('close_window')+'"></div>'+title+'</th></tr>'+
                     '<tr><td class="pit-contents-block" id="pcntb'+id+'"><div style="width: '+w+'; height: '+h+'"><div class="pit-loading" id="pldr'+id+'"></div>'+
                     '<div class="pit-error" id="perr'+id+'"><div class="pit-error-title" id="perrtitle'+id+'"></div><div class="pit-error-text" id="perrtext'+id+'"></div>'+
                     '<div class="pit-error-btn"><button onclick="closePopup('+id+')">'+_text('close_window')+'</button></div></div>'+
                     '<div class="pit-contents" id="pcnt'+id+'"></div></div></td></tr></table></td></tr></table>';
    var off = document.viewport.getScrollOffsets();
    $('overlay-content-container').setStyle({'margin':' -'+off[1]+'px 0px 0px -'+off[0]+'px'});
    $('overlay-container').addClassName('overlay-container');
    Insertion.After($('overlay-container'),pElm);
    var cElm = $(contents);
    if (cElm)
    {
        var te = new Element('div',{'id':'ptmp_'+id});
        te.setStyle({'width':'0px','height':'0px','display':'none'});
        Insertion.Before(cElm,te);
        $('pcnt'+id).appendChild(cElm);
        cElm.show();
        setPopupLoading(id,(properties.loading||false));
        $('perr'+id).hide();
    };
    pElm.setStyle({'visibility':'visible'});
    return(id);
};

function closePopup(id)
{
    var v = popups[id];
    if (v)
    {
        var e = v[0];
        var eid = v[1];
        var ce = $(eid);
        var te = $('ptmp_'+id);
        if ((ce) && (te))
        {
            Insertion.After(te,ce);
            ce.hide();
            te.parentNode.removeChild(te);
        };
        e.parentNode.removeChild(e);
        popups[e] = null;
        ajaxStatus[id] = undefined;
        popupData[id] = undefined;
        intervals[id].each(
            function(k,v){
                clearPopupInterval(k,v);
            }
        );
        intervals[id] = undefined;
    };
    nPopups--;
    if (!nPopups)
    {
        var sX = Math.abs(parseInt($('overlay-content-container').style.marginLeft));
        var sY = Math.abs(parseInt($('overlay-content-container').style.marginTop));
        $('overlay-content-container').setStyle({'margin':'auto'});
        $('overlay-container').removeClassName('overlay-container');
        window.scrollTo(sX,sY);
    };
    return(false);
};

function setPopupLoading(id,loading)
{
    var le = $('pldr'+id);
    var ce = $('pcnt'+id);
    if (loading)
        {
            le.show();
            ce.hide();
        }
    else
        {
            le.hide();
            ce.show();
        };
};

function setPopupError(id,message)
{
    $('perrtitle'+id).update(_text('error_title'));
    $('perrtext'+id).update(_text(message));
    $('perr'+id).show();
    $('pldr'+id).hide();
    $('pcnt'+id).hide();
};

function getCurrentPopup()
{
    return(nPopups-1);
};

function setPopupInterval(pID,iID,iCommand,time)
{
    if (intervals[pID]==undefined)
        intervals[pID] = new Array();
    if (intervals[pID][iID]==undefined)
        intervals[pID][iID] = setInterval(iCommand,time);
};

function clearPopupInterval(pID,iID)
{
    if (intervals[pID]==undefined)
        return;
    if (intervals[pID][iID]==undefined)
        return;
    clearInterval(intervals[pID][iID]);
    intervals[pID][iID] = undefined;
};

function setAjaxStatus(gID,sID,sValue)
{
     if (ajaxStatus[gID]==undefined)
        ajaxStatus[gID] = new Array();
    ajaxStatus[gID][sID] = sValue;
};

function getAjaxStatus(gID,sID)
{
     if (ajaxStatus[gID]==undefined)
        return(null);
     if (ajaxStatus[gID][sID]==undefined)
        return(null);
    return(ajaxStatus[gID][sID]);
};

function setAjaxFailure(pID)
{
    setPopupError(pID,'ajax_error');
};

function setPopupData(pID,n,v)
{
     if (popupData[pID]==undefined)
        popupData[pID] = new Array();
    popupData[pID][n] = v;
};

function getPopupData(pID,n)
{
     if (popupData[pID]==undefined)
        return(null);
     if (popupData[pID][n]==undefined)
        return(null);
    return(popupData[pID][n]);
};

function ___ife()
{
    var e = $A(formError.fields);
    var add = (formError.counter-- % 2);
    if (formError.counter==0)
    {
        e.each(function(v){$(v).removeClassName('form-error')});
        $(formError.submit).writeAttribute('disabled',false);
        clearTimeout(formError.timeout);
        return;
    };
    e.each(function(v){if (add) {$(v).addClassName('form-error');} else {$(v).removeClassName('form-error');};});
    formError.timer = setTimeout('___ife()',formError.timeout);
};

function indicateFormErrors(fields,submit)
{
    formError.fields = fields;
    formError.submit = submit;
    formError.counter = 5;
    formError.timer = setTimeout('___ife()',formError.timeout);
    $(formError.submit).writeAttribute('disabled',true);
};

function emptySelect(id,def)
{
    var e = $(id);
    if (!e)
        return;
    $(e).update();
    if (def)
        e.appendChild(new Element('option',{value:'--'}).update('&#160;'));
};

function showBuyGamePopup(gID,gTitle,gLang)
{
    var pID = showPopup(gTitle,'buyGamePopup',{w:700,h:250,loading:true});
    setPopupData(pID,'app',gID);
    setPopupData(pID,'lang',gLang);
// Load game box image
    new Ajax.Request('/ajax.php',
    {
        method:'get',
        parameters:{type:'app-box',id:gID,gid:pID,lang:getPopupData(pID,'lang'),r:Math.random()},
        onSuccess: function(transport){
            try {
                var r = transport.responseText.evalJSON();
                $('bgGameBox').update();
                $('bgGameBox').appendChild(new Element('img',{'src':r.src,'width':r.width,'height':r.height,'border':0,'alt':r.title,'title':r.title,'onload':"setAjaxStatus("+r.gid+",'app-box-loaded',true)"}));
                setAjaxStatus(r.gid,'app-box-loaded',true);
            } catch(e) {setAjaxFailure(pID);};
        },
        onFailure: function(transport){ setAjaxFailure(pID); }
    });
// Load list of supported handsets
    new Ajax.Request('/ajax.php',
    {
        method:'get',
        parameters:{type:'supported-handsets',id:gID,gid:pID,lang:getPopupData(pID,'lang'),r:Math.random()},
        onSuccess: function(transport){
            try {
                var r = transport.responseText.evalJSON();
                setPopupData(r.gid,'devices',r.devices);
                setPopupData(r.gid,'vendor',r.s_vendor);
                setPopupData(r.gid,'device',r.s_device);
                setAjaxStatus(r.gid,'supported-handsets',true);
            } catch(e) {setAjaxFailure(pID);};
        },
        onFailure: function(transport){ setAjaxFailure(pID); }
    });
// Load list of countries and network operators, supported by billing
    new Ajax.Request('/ajax.php',
    {
        method:'get',
        parameters:{type:'billing-countries',id:gID,gid:pID,lang:getPopupData(pID,'lang'),r:Math.random()},
        onSuccess: function(transport){
            try {
                var r = transport.responseText.evalJSON();
                setPopupData(r.gid,'countries',r.countries);
                setPopupData(r.gid,'country',r.s_country);
                setPopupData(r.gid,'operator',r.s_operator);
                setAjaxStatus(r.gid,'billing-countries',true);
            } catch(e) {setAjaxFailure(pID);};
        },
        onFailure: function(transport){ setAjaxFailure(pID); }
    });
    setPopupInterval(pID,'bg_s1','buyGameStep1()',100);
};

function buyGameStep1()
{
    var pID = getCurrentPopup();
//alert(getAjaxStatus(pID,'app-box-loaded')+"\n"+getAjaxStatus(pID,'supported-handsets')+"\n"+getAjaxStatus(pID,'billing-countries'));
// Check if all required AJAX requests are completed
    if ((getAjaxStatus(pID,'app-box-loaded')) &&
        (getAjaxStatus(pID,'supported-handsets')) &&
        (getAjaxStatus(pID,'billing-countries')))
    {
        clearPopupInterval(pID,'bg_s1');
// Setup lists of phone vendors and models
        var devices = $H(getPopupData(pID,'devices'));
        var sv = getPopupData(pID,'vendor');
        var sd = getPopupData(pID,'device');
        emptySelect('bgVendor',false);
        emptySelect('bgModel',true);
        if (devices.size()>1)
            $('bgVendor').appendChild(new Element('option',{value:'--'}).update(_text('please_select')));
        devices.each(function(v){$('bgVendor').appendChild(new Element('option',{value:v.key,selected:(v.key==sv)}).update(v.value.title))});
        if (sd)
            bgVendorChange();
// Setup lists of billing countries and operators
        var countries = $H(getPopupData(pID,'countries'));
        var sc = getPopupData(pID,'country');
        var so = getPopupData(pID,'operator');
        emptySelect('bgCountry',false);
        emptySelect('bgOperator',true);
        if (countries.size()>1)
            $('bgCountry').appendChild(new Element('option',{value:'--'}).update(_text('please_select')));
        countries.each(function(v){$('bgCountry').appendChild(new Element('option',{value:v.key,selected:(v.key==sv)}).update(v.value.title))});
        if (sc)
            bgCountryChange();
        $('buyGameStep1').show();
        $('buyGameStep2').hide();
        setPopupLoading(pID,false);
    };
};

function buyGameStep1Submit()
{
    var errors = new Array();
    ['bgVendor','bgModel','bgCountry','bgOperator'].each(function(v){var fv=$F(v); if((!fv) || (fv=='--')) errors[errors.length]=v;});
    if (errors.length)
    {
        indicateFormErrors(errors,'bgStep1Submit');
        return(false);
    };
    var pID = getCurrentPopup();
    setPopupLoading(pID,true);
    $('buyGameStep1').hide();
    $('buyGameStep2').show();
// Save gathered order information
    new Ajax.Request('/ajax.php',
    {
        method:'post',
        asynchronous:false,
        parameters:{type:'save-order',gid:pID,app:getPopupData(pID,'app'),vendor:$F('bgVendor'),model:$F('bgModel'),country:$F('bgCountry'),operator:$F('bgOperator'),lang:getPopupData(pID,'lang'),r:Math.random()},
        onSuccess: function(transport){
            try {
                var r = transport.responseText.evalJSON();
                if (r.ok)
                    setPopupData(pID,'order-id',r.order);
                else
                    setPopupError(pID,'error_save_order');
                setAjaxStatus(r.gid,'save-order',true);
            } catch(e) {setAjaxFailure(pID);};
        },
        onFailure: function(transport){ setAjaxFailure(pID); }
    });
// Load list of countries and network operators, supported by billing
    new Ajax.Request('/ajax.php',
    {
        method:'get',
        parameters:{type:'psms-info',gid:pID,order:getPopupData(pID,'order-id'),lang:getPopupData(pID,'lang'),r:Math.random()},
        onSuccess: function(transport){
            try {
                var r = transport.responseText.evalJSON();
                if (r.ok)
                    {
                        setPopupData(r.gid,'psms-text',r.text);
                        setPopupData(r.gid,'psms-number',r.number);
                        setPopupData(r.gid,'psms-price',(r.t_price)?r.t_price:r.price);
/*
                        setPopupData(r.gid,'psms-tax',r.tax);
                        setPopupData(r.gid,'psms-total-price',r.t_price);
*/
                        setAjaxStatus(r.gid,'psms-info',true);
                    }
                else
                    setPopupError(pID,'error_get_psms');
            } catch(e) {setAjaxFailure(pID);};
        },
        onFailure: function(transport){ setAjaxFailure(pID); }
    });
    setPopupInterval(pID,'bg_s2','buyGameStep2()',100);
};

function buyGameStep2()
{
    var pID = getCurrentPopup();
// Check if all required AJAX requests are completed
    if ((getAjaxStatus(pID,'save-order')) &&
        (getAjaxStatus(pID,'psms-info')))
    {
        clearPopupInterval(pID,'bg_s2');
        $('bgPSMSText').update(getPopupData(pID,'psms-text'));
        $('bgPSMSNumber').update(getPopupData(pID,'psms-number'));
        $('bgPSMSPrice').update(getPopupData(pID,'psms-price'));
/*
        var tax = getPopupData(pID,'psms-tax');
        if (tax)
            {
                $('bgPSMSTax').update(tax);
                $('bgPSMSTotalPrice').update(getPopupData(pID,'psms-total-price'));
            }
        else
            $('bgPSMSTaxInfo').hide();
*/
        $('buyGameStep1').hide();
        $('buyGameStep2').show();
        setPopupLoading(pID,false);
    };
};

function bgVendorChange()
{
    var v = $F('bgVendor');
    var pID = getCurrentPopup();
    var devices = getPopupData(pID,'devices');
    var sd = getPopupData(pID,'device');
    emptySelect('bgModel',true);
    if (devices[v]!=undefined)
    {
        emptySelect('bgModel',false);
        var models = $H(devices[v]['devices']);
        if (models.size()>1)
            $('bgModel').appendChild(new Element('option',{value:'--'}).update(_text('please_select')));
        models.each(function(v){$('bgModel').appendChild(new Element('option',{value:v.key,selected:(v.key==sd)}).update(v.value))});
    };
};

function bgCountryChange()
{
    var c = $F('bgCountry');
    var pID = getCurrentPopup();
    var countries = getPopupData(pID,'countries');
    var so = getPopupData(pID,'operator');
    emptySelect('bgOperator',true);
    if (countries[c]!=undefined)
    {
        emptySelect('bgOperator',false);
        var operators = $H(countries[c]['operators']);
        if (operators.size()>1)
            $('bgOperator').appendChild(new Element('option',{value:'--'}).update(_text('please_select')));
        operators.each(function(v){$('bgOperator').appendChild(new Element('option',{value:v.key,selected:(v.key==so)}).update(v.value))});
    };
};
