$(function(){
    $("#Memail").glInputDefText(2);
    $("#Mphone").glInputDefText(5);
    $("#macAddress").glInputDefText(2);
})

function dwnVer(id)
{
    return  $("#divDownloadLinks *[ns3=version]:eq(" + id + ")").html();
}


function dwnSpeed()
{
    var ver = jQuery.browser.version;
    return (ver >= 6 && ver < 7) ? 30 : 1000;
}

function dwnSpeedOut()
{
    var ver = jQuery.browser.version;
    return (ver >= 6 && ver < 7) ? 30 : 0;
}

function goSetSelected(s, outlineDiv, linkDiv)
{
    $('#compae').html(s);
    $(outlineDiv).fadeIn(1);
    $(linkDiv).addClass('selected');
}


function dwnUnSelectAll()
{
    $('#devices a').removeClass('selected');
    $("#content *[wefi='content']").fadeOut(dwnSpeedOut());

}

function goWindows()
{
    dwnUnSelectAll();
    goSetSelected(' Windows Connection Manager', '#download_windows', '#windowsLink');
}

function goMac()
{
    dwnUnSelectAll();
    goSetSelected('AirPort', '#download_mac', '#macLink');
    $("#linkW").attr('href', "compare.php#mac");
}

function goMobile()
{
    dwnUnSelectAll();
    goSetSelected(' other connection managers', '#download_mobile', '#mobileLink');
    $("#linkW").attr('href', "compare.php#wm")
}

function dwnSelectCat(cat)
{

//    console.log(cat);
    switch (cat)
            {
        case 'mac':
            goMac();
            break;
        case 'mobile':
        case 'nokia':
        case 'android':
            goMobile();
            break;
        default :
            goWindows();
            break;
    }
}

function dwnUrl(id)
{
    return $("#divDownloadLinks *[ns3=url]:eq(" + id + ")").html();
}

function dwnSetLinks()
{
}

function dwMobile_Onload()
{
    dwnOnload($("#Mphone"), $("#Memail"), $("#MPCEmail"));
}

function onloadPC()
{
    dwnSelectCat(glParseQuery('cat'));
    dwnSetLinks();
}

function dwnOnload(phone, email, pcemail)
{
    $("#smsForm select").attr("disabled", true);
    dwReset(phone);
    dwReset(email);
    dwReset(pcemail);
    if ((glParseQuery('cat') == "mobile") || (glParseQuery('cat') == "nokia") || (glParseQuery('cat') == "android"))
        setTimeout("dwInitDD()", 500);
}

function dwInitDD()
{
    $.get("/download/country.ajax.php", function(html) { dwMDrop(html); });
    if (gUser.data.email)
        $("#Memail").val(gUser.data.email);
    
    if(glParseQuery('cat') == "nokia")
    {   
        $("#dwMobileOS").val("1");
        mobileCheckPcOS();
    }        
    else if(glParseQuery('cat') == "android")
    {
        $("#dwMobileOS").val("3");
        mobileCheckPcOS();  
    }       
}

$(function(){
    $("#macAddress").glInputDefText(2);
    gUser.onLoggin(function(){
        $("#macAddress").val(gUser.data.email);   
    });
    gUser.onLogout(function(){
        $("#macAddress").val("");
    });
})

function dwMDrop(sTable)
{
    dwDrop(sTable, $("#Mcountry"))
}

function dwDrop(sTable, obj)
{
    $("#smsForm option").remove();
    $.each($(sTable).find("tbody>tr"), function(i, tr) {
        var cid = $($(tr).find("td")[3]).html();
        var cname = $($(tr).find("td")[1]).html();
        obj.append("<option value='" + $.glTrim(cid) + "'>" + $.glTrim(cname) + "</option>")
    });
    $.post("/global/php/nusoap/ip.ajax.php",{},function(x){
        dwDropSetDef(x.Envelope.Body.ipToLocationResponse.locationCountry, obj);
    },'json');
}

function dwDropSetDef(dwCountry, obj)
{
//    if (!(($.browser.msie) && ($.browser.version == 6)))
        if(dwCountry)
            obj.find("option:contains('" + dwCountry + "'):first")[0].selected = true;
    dwDropChnage(obj, true)
    $("#main select").attr("disabled", false);
}

function dwDropChnage(obj, setF)
{
    var oPre = "";
    oPre = $("#Mpre");
    oPre.val($.glTrim($(obj).val()));
//    if (!setF)
//        (glParseQuery('cat') == "mobile") ? $("#wmphone").focus() : $("#Nphone").focus();
}

function dwReset(o)
{
    if (($(o).val() != $(o).attr("t")) && ($(o).val() != "")) return;
    $(o).attr("sel", "");
    $(o).css("color", "gray");
    $(o).val($(o).attr("t"));
}


function dwFocuse(o)
{
    if ($(o).attr("sel"))
        return;
    $(o).attr("sel", "1");
    $(o).val("");
    $(o).css("color", "black");
}

function dwSMSM()
{
    dwSMS($("#Mphone"), $("#Memail"), $("#Mcountry"), $("#Mpre"), 0)
}

function dwSMS(p, e, c, pr, ptype)
{
    if (p.val().slice(0, 1) == "0")
        p.val(p.val().slice(1, p.val().length));
    var cl = new gcList();
    if (c.val() == "0")
        cl.addItem('Please select country');
    if (isNaN(p.val()))
        cl.addItem('Phone number must be digits only');
    if (p.val().length < 8)
        cl.addItem('Phone number must be more then 8 digits');
    if (e.attr("sel"))
        if (!glEmailCheck(e.val()))
            cl.addItem('Not a valid email address');
     if (cl.count)
    {
        glAlert('Error!', 'Please enter/fix following item(s):<br/>' + cl.getList() + '', 235, 330);
        return false;
    }
    glWaitAlert(235, 330);
    var callback = null;

    callback = dw_M_SMSCallback;
    $.post("smsmobile.ajax.php", {cnu:gUser.data.cnu,country:c.find("option").filter(":selected").text(),code:pr.val(),number:p.val(),email:e.val(),ptype:ptype}, callback)
}

function macSubmtRequest()
{
    if (!glEmailCheck($('#macAddress').val())) {
        glAlert('Error!', 'Your email address is invalid')
        return false;
    }
    else {
        glWaitAlert(200, 400);
        var s = $.post("/feedback/feedback.ajax.php", {subject:6,email:$("#macAddress").val(),comments:"please send me Mac client"}, macSubmtRequest_Result);
    }
}


function macSubmtRequest_Result(s)
{
    glCloseWaitAlert();
    if (s == 1)
    {
        glAlert("Thanks for your interest", "We will contact you once the Mac version becomes available.", 200, 400);
        setTimeout(macGoToHome, 3000);
    }
    else
        glAlert("Error", "Please type in your email address", 200, 400);
}


function macGoToHome()
{
    location.href = "/";
}


function mobileCheckPcOS()
{
    if($("#dwMobileOS").val()==='0')
    {
        $("#pcDownload").css("background-image","url(/download/images/download_disabled.png)");
        $("#pcDownload").css("cursor","auto");
        $("#pcDownload").unbind("click");
        $("#mbExtras>div").hide();
    } else {
        $("#pcDownload").css("background-image","url(/download/images/download.png)");
        $("#pcDownload").css("cursor","pointer");
        $("#pcDownload").click(dwMobilePC);
        $("#mbExtras>div").hide();
        if($("#dwMobileOS").val()==='1')
            $("#mbSymbianExtras").show();
        else if($("#dwMobileOS").val()==='2')
            $("#mbWinmoExtras").show();
        else if($("#dwMobileOS").val()==='3')
            $("#mbAndroidExtras").show();
    }
}

function dwMobilePC()
{
    if($("#dwMobileOS").val()==='1')
        dwPC($("#MPCEmail"), 1, dwPCCallbackNokia);
    else if($("#dwMobileOS").val()==='2')
        dwPC($("#MPCEmail"), 2, dwPCCallbackWM);
    else if($("#dwMobileOS").val()==='3')
        dwPC($("#MPCEmail"), 3, dwPCCallbackAndroid);
}


function dwPC(e, ptype, callback)
{
    var cl = new gcList();
    if (e.attr("sel"))
        if (!glEmailCheck(e.val()))
            cl.addItem('Not a valid email address');
    if (cl.count)
    {
        glAlert('Error!', 'Please enter/fix the following item(s):<br/>' + cl.getList() + '', 335, 330);
        return false;
    }
    glWaitAlert(365, 330);
    $.post("smsmobile.ajax.php", {cnu:gUser.data.cnu,email:e.attr("sel") ? e.val() : "NA",ptype:ptype}, callback)
}

function dwPCCallbackWM() {document.location.href = "/download/wm/";}
function dwPCCallbackNokia() {document.location.href = "/download/nokia/";}
function dwPCCallbackAndroid() {document.location.href = "/download/android/";}

function dw_M_SMSCallback(res) {dwSMSCallback(res, "#Mpre", "#Mphone", "#Memail", "/download/?cat=mobile")}
//function dw_M_SMSCallback(res) { dwSMSCallback(res, "#Mpre", "#Mphone", "#Memail", "/download/mobile/") }

function dwSMSCallback(res, pre, phone, email, exp)
{
    glCloseWaitAlert();
    res = $.trim(res);
    if (res.slice(0, 2) != "ID")
    {
        glAlert("Error", res.split(",")[1], 235, 330);
        return;
    }

    var s = "An SMS was sent to mobile ";
    s += "<span style='color:#3FB309'>"
    s += $(pre).val() + "-" + $(phone).val() + ", ";
    s += "</span>"
    s += "please open the link to install WeFi on your mobile. ";
    s += "If you didn't get the SMS ";
    s += "Click <a href='" + exp + "'>here</a>";
    glAlert('Success!', s, 235, 330);
    $(phone).val("");
    $(email).val("");
    dwReset($(phone));
    dwReset($(email));
}