﻿function MainPageLoad() 
{
    if (window.location.host.toLowerCase() != "www.mightyplace.com" && window.location.host.substring(0, 3).toUpperCase() != 'LOC')
        window.location.href = window.location.protocol + "//www.mightyplace.com" + window.location.pathname;

    $(document).ready(function () 
    {
        $("#btnShowMessageShop").colorbox({ inline: true, overlayClose: false, close: null, html: true, href: "#divShopMerchant",
            onLoad: function() 
            {
                $('#cboxClose').remove();
            }
            });
        });

        $('#txtPassword').keypress(function(e) 
        {
            if (e.which == 13) 
            {
                e.which = 0;
                Signin();
                return false;
            }
        });

        if ($get('hiddenTab').value == '-1') //forgot pw
        {
        $('#txtForgotPassword').keypress(function(e) 
        {
            if (e.which == 13) 
            {
                e.which = 0;
                GetSecurityQuestions();
                $('#divPleaseWait').dialog('close');
                return false;
            }
        });
    }

    var qsParm = new Array();
    var query = window.location.search.substring(1);
    var parms = query.split('&');
    for (var i = 0; i < parms.length; i++) 
    {
        var pos = parms[i].indexOf('=');
        if (pos > 0) 
        {
            var key = parms[i].substring(0, pos);
            var val = parms[i].substring(pos + 1);
            qsParm[key] = val;
        }
    }
    if (parms.length > 0) 
    {
        if ($get('hiddenTab').value == '0')
        {
            if (qsParm.r != null) 
            {
                ShowWaitDialog();
                MightyPlace.WebServices.CommonService.SaveReferralUser_ID(qsParm.r, SaveReferralComplete, WebError);
                return;
            }
            
        }
        if ($get('hiddenTab').value == '6') 
        {
            if ($get('hiddenSubTab').value == '7') 
            {
                if (qsParm.m != null)
                    $get('hiddenMerchant_ID').value = qsParm.m;
            }
            if ($get('hiddenSubTab').value == '0') 
            {
                if (qsParm.u != null && qsParm.m != null) 
                {
                    StartShopping(qsParm.u, qsParm.m);
                    return;
                }
            }
        }
        if ($get('hiddenTab').value == '-2')  //activate account
        {
            ShowWaitDialog();
            SelectTab($get('hiddenTab').value, $get('hiddenSubTab').value);
            return;
        }
    }    
    
    //Populate hidden fields from session or cookie (if exists)
    ShowWaitDialog();
    MightyPlace.WebServices.LoginService.GetCurrentAccount($get('hiddenTab').value, $get('hiddenSubTab').value, GetCurrentAccountComplete, WebError);
}

function ResetSession() 
{
    if ($get('hiddenLoggedIn').value == 1) 
        MightyPlace.WebServices.LoginService.SaveSession(ResetSessionComplete, WebError);
}

function ResetSessionComplete(results) //results = true (user still logged in)
{
    if (results[1] > 0) 
    {
        $get('lblNewMessages').innerHTML = results[1].toString() + " New Message(s)";
        $get('lblNewMessages').style.display = 'block';
        $get('tab_row2').style.display = 'block';
    }
    else 
    {
        $get('lblNewMessages').style.display = 'none';
        $get('tab_row2').style.display = 'none';
    }


    if (results[0] == 1) //reset session for another 15 mins.
    {
        if ($get('hiddenTab').value == '2' && $get('hiddenSubTab').value == '0') 
        {
            GetSessionFolders();
        }
        else 
        {
            window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
            $get('hiddenWindowIntervalID').value = window.setInterval("ResetSession();", 900000); //15 minutes
        }
    }
    else 
    {
        window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    }
}

function SaveReferralComplete() 
{
    MightyPlace.WebServices.LoginService.GetCurrentAccount($get('hiddenTab').value, $get('hiddenSubTab').value, GetCurrentAccountComplete, WebError);
}

function GetCurrentAccountComplete(results) 
{
    if (results.currentLogin.User_ID > 0) 
    {
        SetUserFields(results);
        if ($get('hiddenTab').value == "-1")
            SelectTab($get('hiddenTab').value, $get('hiddenSubTab').value);
        //MightyPlace.WebServices.LoginService.GetUserTabs($get('hiddenTab').value, $get('hiddenSubTab').value, GetTabsComplete, WebError); //logged in
        else 
        {
            if (results.currentUser.EmailActive == false && results.currentLogin.DefaultTab_ID == 2) 
            {
                MessageBox("Free Email is not currently active for this account.  To activate free email, go to your profile.", 'Y', 0, 0, null, "Email Not Active");
                return;
            }
            else 
            {
                if (results.currentUser.EmailActive == true)
                    $get('tab_row2').style.display = 'block';
                SelectTab(results.currentLogin.DefaultTab_ID, results.currentLogin.DefaultSubTab_ID);
            }
            //MightyPlace.WebServices.LoginService.GetUserTabs(results.currentLogin.DefaultTab_ID, results.currentLogin.DefaultSubTab_ID, GetTabsComplete, WebError); //logged in
        }
    }
    else
    {
        $get('hiddenLoggedIn').value = '0';
        $get('hiddenUser_ID').value = '0';
        $get('hiddenUserCode').value = '';
        $get('hiddenZipCode').value = '';
        $get('hiddenCountry_ID').value = '0';
        $get('hiddenCountryDescription').value = '';
        $get('hiddenName').value = '';
        $get('hiddenLanguage').value = '0';
        $get('divWelcome').style.display = 'none';
        $get('lblProfileName').value = '';
        $get('pnlSignIn').style.display = 'block';
        $get('lblInvalidUserName').style.display = 'none';
        $get('txtUserName').focus();

        if (results.currentLogin.User_ID == 0)
        {
            //if ($get('hiddenTab').value == '-1') //forgot pw, etc.. non-tabbed page.
            if ($get('hiddenTab').value == '-1' || $get('hiddenTab').value == '-2') //forgot pw, etc.. non-tabbed page or -2=activate
                SelectTab($get('hiddenTab').value, $get('hiddenSubTab').value);
            //MightyPlace.WebServices.LoginService.GetUserTabs($get('hiddenTab').value, $get('hiddenSubTab').value, GetTabsComplete, WebError); //new user
            else
                SelectTab(results.currentLogin.DefaultTab_ID, results.currentLogin.DefaultSubTab_ID);
                //MightyPlace.WebServices.LoginService.GetGuestTabs(results.currentLogin.DefaultTab_ID, results.currentLogin.DefaultSubTab_ID, GetTabsComplete, WebError);  //not logged in
        }
        else 
            SelectTab($get('hiddenTab').value, $get('hiddenSubTab').value);
            //MightyPlace.WebServices.LoginService.GetUserTabs($get('hiddenTab').value, $get('hiddenSubTab').value, GetTabsComplete, WebError); //new user
    }
}

function SetUserFields(results) 
{
    window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    $get('hiddenWindowIntervalID').value = window.setInterval("ResetSession();", 900000); //15 minutes    
    if (results.currentLogin.isLoggedIn == true)
        $get('hiddenLoggedIn').value = '1';
    else
        $get('hiddenLoggedIn').value = '0';
    $get('hiddenUser_ID').value = results.currentLogin.User_ID;
    $get('hiddenUserCode').value = results.currentLogin.UserCode;
    $get('hiddenCountry_ID').value = results.currentLogin.Country_ID;
    $get('hiddenCountryDescription').value = results.currentLogin.CountryDescription;
    $get('hiddenZipCode').value = results.currentLogin.ZipCode;
    $get('hiddenLanguage').value = results.currentLogin.LanguageID;
    $get('hiddenAccountType').value = results.currentUser.AccountType;
    if ($get('hiddenAccountType').value > 1)
        $get('hiddenName').value = results.currentUser.CompanyName;
    else
        $get('hiddenName').value = results.currentUser.FirstName + ' ' + results.currentUser.LastName;
    if (results.currentUser.EmailActive == true) 
    {
        $get('tab_row2').style.display = 'block';
        if (results.currentUser.NewMailMessages > 0) 
        {
            $get('lblNewMessages').innerHTML = results.currentUser.NewMailMessages.toString() + " New Message(s)";
            $get('lblNewMessages').style.display = 'block';
        }
        else
            $get('lblNewMessages').style.display = 'none';
    }
    else {
        $get('tab_row2').style.display = 'none';
        $get('lblNewMessages').style.display = 'none';
    }
        
    $get('divMasterBalance').innerHTML = results.currentUser.Balance.toFixed(2);
    $get('lblProfileName').value = $get('hiddenName').value;

    $get('pnlSignIn').style.display = 'none';
    $get('divWelcome').style.display = 'block';
}

function GetMasterFeeds() 
{
    if ($get('hiddenZipCode').value.length > 0)
        MightyPlace.WebServices.CommonService.GetMasterFeeds($get('hiddenZipCode').value, GetMasterFeedsComplete, WebError);
}

function GetMasterFeedsComplete(results) 
{
    window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    $get('hiddenWindowIntervalID').value = window.setInterval("ResetSession();", 900000); //15 minutes    
    if (results != null)
        $get('divMainWeather').innerHTML = results[0];
    else
        $get('divMainWeather').innerHTML = "";

    $('#divPleaseWait').dialog('close');
}

function WebError(results) 
{
    if ($get('hiddenWindowIntervalID') == null)
        return;
    window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    $get('hiddenWindowIntervalID').value = window.setInterval("ResetSession();", 900000); //15 minutes    
    $('#divPleaseWait').dialog('close');
    MessageBox("A system error has occurred.  Please send an email to CustomerService@MightyPlace.com describing what happend and how you got to this error so that our development team can look into the issue.<br /><br />You may try your request again later.<br /<br />Thank You,<br /><br />The Mighty Place.", 'Y');
}

function WebComplete(results) 
{
    if ($get('hiddenWindowIntervalID') == null)
            return;
    window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    $get('hiddenWindowIntervalID').value = window.setInterval("ResetSession();", 900000); //15 minutes     
    $('#divPleaseWait').dialog('close');
}

function GetTabsComplete(results) 
{
    //$get('divTabs').innerHTML = results[0];
    window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    $get('hiddenWindowIntervalID').value = window.setInterval("ResetSession();", 900000); //15 minutes     
    SelectTab(results[1], results[2]);
}

function Signin() 
{
    ShowWaitDialog();
    MightyPlace.WebServices.LoginService.GetAccountByUserNamePassword($get('txtUserName').value, $get('txtPassword').value, SigninResult);
    return false;
}

function SigninResult(results, eventArgs) 
{
    // Page element to display feedback.
    if (results.currentLogin.User_ID == 0) 
    {
        $get('lblInvalidUserName').style.display = 'block';
        $('#divPleaseWait').dialog('close');
        return false;
    }
    CompleteSignin($get('chkRememberMe').checked, results.currentLogin.DefaultTab_ID, results.currentLogin.DefaultSubTab_ID, results);
    return false;
}

function Signin_Dialog() 
{
    ShowWaitDialog();
    MightyPlace.WebServices.LoginService.GetAccountByUserNamePassword($get('txt_dg_UserName').value, $get('txt_dg_Password').value, Signin_dg_Complete, WebError);
    return false;
}

function Signin_dg_Complete(results) 
{
    // Page element to display feedback.
    $('#divPleaseWait').dialog('close');
    if (results.currentLogin.User_ID == 0) 
    {
        $get('lbl_dg_Error').style.display = 'block';
        return false;
    }
    $('#divLogin').dialog('close');
    CompleteSignin($get('chk_dg_RememberMe').checked, $get('hiddenNewTabID').value, $get('hiddenNewSubTabID').value, results);
}

function Signin_dg_Cancel(results) 
{
    $('#divLogin').dialog('close');
    if ($get('hiddenTab').value == 4) //news
        $get('hiddenSubTab').value = 0;
}

//function SignOutMessage() 
//{
//    var output = "<table><tr style='vertical-align:top;'><td>WARNING: Your session has expired due to 20 minutes of inactivity.<br />You must sign in again.</td>";
//    output += "<td style='text-align:right;'><div style='width:125px; text-align:right;'><img id='Img2' src='/Images/Common/sad.gif' alt='STOP' /></div></td></tr></table>";
//    MessageBox(output, 'N', null, null, 400, 'Session logout due to inactivity.', 200);
//}

function CompleteSignin(RememberMe, tabid, subtabid, results) 
{
    if (results.currentUser.AccountStatus < 2)  //0=new, 1=current
        SetUserFields(results);
    if (results.currentUser.AccountStatus == 1) //current
        SelectTab(tabid, subtabid);
        //MightyPlace.WebServices.LoginService.GetUserTabs(tabid, subtabid, GetTabsComplete, WebError); //logged in
    else
    {
        var lblerr = "";
        if (results.currentUser.AccountStatus == 0) //New
        {
            lblerr = "This account has not yet been activated.<br /><br />You will not have full permission to do everything.<br /><br />You must click on the link in the email that was sent to you to activate your account.<br><br><br />";
            lblerr += "If you need another email sent, please click <a onclick=\"NewUserEmail();\" style=\"color:NAVY; text-decoration:underline;\" onmouseover=\"javascript:this.style.cursor='pointer'\" ";
            lblerr += "id=\"lnkNewUser\">HERE</a>";
        }
        else if (results.currentUser.AccountStatus == 2) //Password locked
        {
            lblerr = "This account has been locked because of several invalid login attempts.<br /><br />You must click the 'Forgot Username / Password' link to access your account.";
        }
        else if (results.currentUser.AccountStatus == 3) //admin locked
        {
            lblerr = "This account is currently locked and can not be accessed at this time.";
        }
        else //4=user closed
        {
            lblerr = "This account has been closed at the request of the member.<br /><br />If you would like to re-activate this account, please contact customer service at CustomerService@MightyPlace.com";
        }
        $('#divPleaseWait').dialog('close');
        $get('lblErrors').innerHTML = lblerr;
        $get('divStopImage').src = "/Images/Common/stop.png";
        $('#divStop').dialog({
            modal: true, title: "<div style='color:navy;'>STOP!</div>", draggable: false, resizable: false, show: 'Transfer', hide: 'Transfer', height: 'auto', width: '550px', position: 'center',
            close: function (event, ui) {
                if (results.currentUser.AccountStatus > 1) //pw, admin, or user closed
                    SignOut();
                else
                    SelectTab(tabid, subtabid);
                //MightyPlace.WebServices.LoginService.GetUserTabs(tabid, subtabid, GetTabsComplete, WebError); //logged in
            }
        })
    }
}

//function SetMemberCookie(results) 
//{
//    var today = new Date();
//    var expr = new Date(today.getTime() + (365 * 24 * 60 * 60 * 1000));
//    
//    var cvalue = "MPCL=0%" + results.User_ID;
//    cvalue += "%" + results.DefaultTab_ID;
//    cvalue += "%" + results.DefaultSubTab_ID;
//    cvalue += "%" + results.LanguageID;
//    cvalue += "%" + results.Country_ID;
//    cvalue += "%" + results.ZipCode;
//    cvalue += "%" + results.CountryDescription;
//    cvalue += "%" + results.UserCode;
//    //document.cookie = cvalue + "; expires=" + expr.toGMTString() + "; path=/";
//}

function SignOut() 
{
    ShowWaitDialog();
    window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    $get('hiddenWindowIntervalID').value = window.setInterval("ResetSession();", 900000); //15 minutes     
    var date = new Date();  // current date & time
    date.setTime(date.getTime() - 1);
    //document.cookie = "MPCL=0; expires=" + date.toString() + "; path=/";
    document.cookie = "MPCL=0; expires=" + date.toString() + "; path=/";
    document.cookie = "MPCL; expires=" + date.toString() + "; path=/";
    
    $get('hiddenUser_ID').value = '0';
    $get('hiddenUserCode').value = '';
    $get('hiddenZipCode').value = '';
    $get('hiddenCountry_ID').value = '0';
    $get('hiddenAccountType').value = '0';
    $get('hiddenCountryDescription').value = '';
    $get('hiddenName').value = '';
    $get('hiddenLanguage').value = '0';

    
//    $get('divMainWeather').innerHTML = "";

//    $get('divWelcome').style.display = 'none';
//    $get('lblProfileName').value = '';
//    $get('pnlSignIn').style.display = 'block';
//    $get('lblInvalidUserName').style.display = 'none';

//    $get('txtPassword').value = '';
//    $get('txtUserName').value = '';
//    $get('txtUserName').focus();
//    $get('chkRememberMe').checked = true;
//    $get('chk_dg_RememberMe').checked = true;

    MightyPlace.WebServices.LoginService.Logout('N', LogoutComplete, WebError);
    //document.cookie = "MPCL = ''; expires=-1; path=/";
    
    //MightyPlace.WebServices.LoginService.GetGuestTabs(0, 0, GetTabsComplete, WebError);
}

function LogoutComplete(results) 
{
    window.location.href = "/Default.aspx";    
}

function NewUser(subtab) 
{
//    var date = new Date();  // current date & time
//    date.setTime(date.getTime() - 1);
    //    document.cookie = "MPCL=0; expires=" + date.toString() + "; path=/";
    $get('hiddenNewSubTabID').value = subtab;
    
    var date = new Date();  // current date & time
    date.setTime(date.getTime() - 1);
    //document.cookie = "MPCL=0; expires=" + date.toString() + "; path=/";
    document.cookie = "MPCL=0; expires=" + date.toString() + "; path=/";
    document.cookie = "MPCL; expires=" + date.toString() + "; path=/";

    MightyPlace.WebServices.LoginService.Logout('Y', NewUserContinue, WebError);
}

function NewUserContinue(results)
{
    
    $get('hiddenUser_ID').value = '0';
    $get('hiddenUserCode').value = '';
    $get('hiddenZipCode').value = '';
    $get('hiddenCountry_ID').value = '';
    $get('hiddenCountryDescription').value = '';
    $get('hiddenName').value = '';
    $get('hiddenLanguage').value = '0';
    $get('hiddenAccountType').value = '0';

    $get('divWelcome').style.display = 'none';
    $get('lblProfileName').value = '';
    $get('pnlSignIn').style.display = 'block';
    $get('lblInvalidUserName').style.display = 'none';

    $get('txtPassword').value = '';
    $get('txtUserName').value = '';
    $get('chkRememberMe').checked = true;
    $get('chk_dg_RememberMe').checked = true;

    LoadTab(new Array(1, $get('hiddenNewSubTabID').value)); //Load the empty profile tab.. bypass login check.
}

function SetSpanish() 
{
    if ($get("ddlLanguage").value == "1") 
    {
        google.language.translate("Current Location:", "en", "es", function (result) 
        {
            if (!result.error) 
                $get("lblLocation").innerHTML = result.translation;
        });

        google.language.translate($get("ctl00_lblWeather").innerText, "en", "es", function (result) 
        {
            if (!result.error) 
                $get("ctl00_lblWeather").innerHTML = result.translation;
        });

        google.language.translate("Home", "en", "de", function (result) 
        {
            if (!result.error) 
                $get("ctl00_lnkHome").innerHTML = result.translation;
        });

        google.language.translate("My Profile", "en", "fr", function (result) 
        {
            if (!result.error) 
                $get("ctl00_lnkMyProfile").innerHTML = result.translation;
        });

        google.language.translate("Personals", "en", "es", function (result) 
        {
            if (!result.error) 
                $get("ctl00_lnkPersonals").innerHTML = result.translation;
        });
        
    }
    else 
    {
        $get("lblLocation").innerHTML = "Current Location:";
        $get("ctl00_lnkHome").innerHTML = "Home";
        $get("ctl00_lnkMyProfile").innerHTML = "My Profile";
        $get("ctl00_lnkPersonals").innerHTML = "Personals";
    }
}

function SelectTab(tabid, subtabid) 
{
    if (tabid == '106')
    {
        FixAds();
        $('#divPleaseWait').dialog('close');
        return;
    }
    if (tabid == '-1') 
    {
        FixAds();
        $('#divPleaseWait').dialog('close');
        return;
    }
    if ($get('hiddenTab').value == '-2') //activate
    {
        FixAds();
        $('#divPleaseWait').dialog('close');
        ActivateAccount();
        return;
    }
    if (tabid == '1') 
    {
        if (subtabid == '-10') 
        {
            UpgradeLoginCheck();
            return;
        }
        else if (subtabid == '-11') 
        {
            AdLoginCheck();
            return;
        }
    }

    if (tabid == $get('hiddenTab').value && subtabid == $get('hiddenSubTab').value) 
    {
        //FixAds(); 
        var rowname = 'tab_row' + tabid;
        $get(rowname).style.color = "Red";

        switch (tabid.toString()) 
        {
            case "0": //Home
                ShowWaitDialog();
                if ($get('hiddenUser_ID').value.length > 0 && $get('hiddenUser_ID').value != '0')
                    $get('divsignuptext').style.display = 'none';
                else
                    $get('divsignuptext').style.display = 'block';
                LoadDefault();
                FixAds(null, 4);
                break;
            case "1": //Profile
                SetNewCaptcha();
                if (subtabid == 0 || subtabid == 10) //MainProfile || MainBusinessProfile
                    ProfileMain();
                else if (subtabid == 11)
                    AdLoginCheck();
                else if (subtabid == 1) //Extended Profile
                {
                    $('#divPleaseWait').dialog('close');
                    ProfileExtended();
                }
                else if (subtabid == -10)
                    UpgradeLoginCheck();
                FixAds();
                return;
                break;
            case "2": //Email
                MailMain();
                $('#divPleaseWait').dialog('close');
                return;
                break;
            case "5": //news
                if (subtabid == 0) //NewsMain
                    NewsMain();
                else //1=SaveLayout
                    SaveLayout();
                FixAds();
                break;
            case "6": //shopping
                if (subtabid == 6) //my account
                    SelectShopLink(6);
                else
                    MainShopping();
                FixAds();
                $('#divPleaseWait').dialog('close');
                break;
            case "7": //classifieds
                MainClassifieds();
                FixAds();  
                $('#divPleaseWait').dialog('close');
                break;
            case "12": //Forums
                $('#divPleaseWait').dialog('close');
                break;
            default:
                FixAds();
                $('#divPleaseWait').dialog('close');
                return;
        }
        return;
    }
    MightyPlace.WebServices.LoginService.isTabLoginRequired(tabid, subtabid, SetTabSuccess, WebError);    
}

function SetTabSuccess(results) 
{
    var newtabid = results[0];
    var newsubtabid = results[1];

    if (results[2] == 1) //1=User Must Login
    {
        FixAds();
        $get('hiddenNewTabID').value = newtabid;
        $get('hiddenNewSubTabID').value = newsubtabid;
        $get('txt_dg_UserName').value = "";
        $get('txt_dg_Password').value = "";
        $get('chk_dg_RememberMe').checked = true;
        $get('lbl_dg_Error').style.display = 'none';
        $('#divPleaseWait').dialog('close');
        $('#divLogin').dialog({ modal: true, title: "<div style='color:navy;'>You must first login</div>", draggable: true, resizable: false, show: 'Transfer', hide: 'Transfer', height: 'auto', width: '370px', position: [450,100] });
//            open: function(event, ui) 
//            {
//                $(".ui-dialog-titlebar-close").hide();
//            } 
//        });
        $('#txt_dg_Password').keypress(function(e) 
        {
            if (e.which == 13) {
                e.which = 0;
                Signin_Dialog();
                return false;
            }
        });
        return;
    }
    window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    MightyPlace.WebServices.LoginService.SelectTab(newtabid, newsubtabid, LoadTab, WebError);    
}

function LoadTab(tabs) 
{
    var rowname = 'tab_row' + tabs[0];
    $get(rowname).style.color = "Red";

    if ($get('hiddenTab').value != '-1' && $get('hiddenTab').value != '106') 
    {
        rowname = 'tab_row' + $get('hiddenTab').value;
        $get(rowname).style.color = "Navy";
    }
    switch (tabs[0])
    {
        case 0: //Home
            window.location.href = "http://" + window.location.host + "/Default.aspx";
            break;
        case 1: //Profile
            if (tabs[1] == 0)
                if ($get('hiddenAccountType').value < 2)
                    window.location.href = "https://" + window.location.host + "/MainPersonalProfile.aspx";
                else
                    window.location.href = "https://" + window.location.host + "/Profiles/MainBusinessProfile.aspx";
            else if (tabs[1] == 10)
                window.location.href = "https://" + window.location.host + "/Profiles/MainBusinessProfile.aspx";
            else if (tabs[1] == 11)
                window.location.href = "https://" + window.location.host + "/Profiles/BusinessAdProfile.aspx";
            else if (tabs[1] == 1) //Extended Profile
                window.location.href = "https://" + window.location.host + "/Profiles/ExtendedProfile.aspx";
            break;
        case 2: //Email
            if (tabs[1] == 0) //mail
            {
                $get('hiddenNewSubTabID').value = 0; //select inbox. any other value than 0 will select folder matching id.
                window.location.href = "http://" + window.location.host + "/Mail.aspx";
            }
            else if (tabs[1] == 1) //manage folders
            {
                window.location.href = "http://" + window.location.host + "/Mail/ManageFolders.aspx";
            }
            break;
        case 3:
            window.location.href = "http://" + window.location.host + "/InstantMessaging.aspx";
            break;
        case 4:
            window.location.href = "http://" + window.location.host + "/InstantMessaging.aspx";
            break;
        case 5:
            window.location.href = "http://" + window.location.host + "/News.aspx";
            break;
        case 6: //Shopping
            if (tabs[1] == 0)
                window.location.href = "http://" + window.location.host + "/Shopping.aspx";
            else if (tabs[1] == 6)
                window.location.href = "http://" + window.location.host + "/Shopping/MyAccount.aspx";
            else if (tabs[1] == 1)
                window.location.href = "http://" + window.location.host + "/Shopping/Rewards.aspx";
            else if (tabs[1] == 2)
                window.location.href = "http://" + window.location.host + "/Shopping/ReferAFriend.aspx";
            else if (tabs[1] == 4)
                window.location.href = "http://" + window.location.host + "/Shopping/Coupons.aspx";
            else if (tabs[1] == 7)
                window.location.href = "http://" + window.location.host + "/Shopping/CreateReward.aspx";
            break;
        case 7: //Classifieds
            window.location.href = "http://" + window.location.host + "/Classifieds.aspx";
            break;
        case 8: //Jobs
            window.location.href = "http://" + window.location.host + "/Jobs.aspx";
            break;
        case 9: //Personals
            window.location.href = "http://" + window.location.host + "/Personals.aspx";
            break;
        case 10: //ChatRooms
            window.location.href = "http://" + window.location.host + "/ChatRooms.aspx";
            break;
        case 11: //Schoolmates
            window.location.href = "http://" + window.location.host + "/Schoolmates.aspx";
            break;
        case 12: //Donations
            window.location.href = "http://" + window.location.host + "/Donations.aspx";
            break;
        case 13: //Forums
            window.location.href = "http://" + window.location.host + "/Forums.aspx";
            break;
        //case 14: //Torrents
            //window.location.href = "/MightyPlace/Torrents.aspx";
        //    break;
        default:
            window.location.href = "http://" + window.location.host + "/Default.aspx";
    }
    //FixAds();
}

function MessageBox(message, includestop, newtab, newsubtab, windowwidth, title, height) 
{
    if (newtab != null && newsubtab != null) 
    {
        $get('hiddenMsgNewTab').value = newtab;
        $get('hiddenMsgNewSubTab').value = newsubtab;
    }
    
    var outtitle = "<div style='color:white; background-color:Navy; font-size:x-large; text-align:center;'>STOP!</div>";
    if (title != null)
        outtitle = "<div style='color:white; background-color:Navy; font-size:x-large; text-align:center;'>" + title + "</div>";
    if (includestop == 'Y') 
    {
        $get('lblErrors').innerHTML = message;
        var boxtype = '#divStop';
        if (windowwidth == null)
            windowwidth = 500;
    }
    else 
    {
        if (title == null)
            outtitle = "<div style='color:white; background-color:Navy; font-size:x-large; text-align:center;'>Information</div>";
        else
            outtitle = "<div style='color:white; background-color:Navy; font-size:x-large; text-align:center;'>" + title + "</div>";
        $get('lblMessageBox').innerHTML = message;
        boxtype = '#divMessageBox';
        if (height == null) 
        {
            $get('divMessageBoxInternal').style.height = 'auto';
            //if (screen.availHeight < 600)
            //    $get('divMessageBoxInternal').style.height = screen.availHeight.toString() + 'px'
            //else
            //    $get('divMessageBoxInternal').style.height = '600px';
        }
        else 
        {
            $get('divMessageBoxInternal').style.height = 'auto';
//            if (screen.availHeight < height) 
//                $get('divMessageBoxInternal').style.height = availHeight + 'px';
//            else
//                $get('divMessageBoxInternal').style.height = height + 'px';
        }
        if (windowwidth == null) 
            windowwidth = 370;
        $get('divMessageBoxInternal').style.width = windowwidth + 'px';
    }
    $('#divPleaseWait').dialog('close');
    //$("#divMessageBox").modal({ modal: true});
//    if (includestop == 'Y')
//        $('#btnShowMessageStop').click();
//    else
    //        $('#btnShowMessage').click();

    $(boxtype).dialog({ modal: true, title: outtitle, draggable: true, resizable: false, show: 'Transfer', hide: 'Transfer', height: 'auto', width: (windowwidth + 20).toString() + 'px', position: 'center',
        close: function (event, ui) 
        {
            if (newtab != null) 
            {
                if (newtab == -1)
                    window.location.href = "/Default.aspx";
                else if (newtab == -2) //activation - signout
                    SignOut();
                else
                    SelectTab(newtab, newsubtab);
            }
        },
        open: function (event, ui) { $(".ui-dialog-titlebar-close").show(); }
    })
    if (includestop == 'N')
        $('#divMessageBoxInternal').scrollTo(0, 0, { easing: 'elasout' }); //specify an easing equation
}

function MessageBoxExternal(message, includestop, newtab, newsubtab, windowwidth, title, height) 
{
    vars = new Array();
    vars[0] = message;
    vars[1] = includestop;
    vars[2] = newtab;
    vars[3] = newsubtab;
    vars[4] = windowwidth;
    vars[5] = title;
    vars[6] = height;
    MightyPlace.WebServices.CommonService.GetExternalMessage(vars, MessageBoxExternalResult, WebError);    
}

function MessageBoxExternalResult(results) 
{
    window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    $get('hiddenWindowIntervalID').value = window.setInterval("ResetSession();", 900000); //15 minutes     
    MessageBox(results[0], results[1], results[2], results[3], results[4], results[5], results[6]); 
}

function ForgotUserNamePassword() 
{
    window.location.href = "/Tools/ForgotUserInfo.aspx";
}

function SetNewCaptcha() 
{
    MightyPlace.WebServices.CommonService.SetNewCaptcha(SetNewCaptchaComplete, WebError);
}

function SetNewCaptchaComplete(results) 
{
    window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    $get('hiddenWindowIntervalID').value = window.setInterval("ResetSession();", 900000); //15 minutes     
    $get('imgCaptcha').src = "/Tools/CaptchaImage/JpegImage.aspx?r=" + results;
}

function GetBalanceDetails() 
{
    //Populate hidden fields from session or cookie (if exists)
    MightyPlace.WebServices.LoginService.GetCurrentAccount($get('hiddenTab').value, $get('hiddenSubTab').value, BalanceDetailsResult, WebError);
    return true;
}

function BalanceDetailsResult(results) 
{
    window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    $get('hiddenWindowIntervalID').value = window.setInterval("ResetSession();", 900000); //15 minutes     
    if (results.currentLogin.User_ID < 1)
        MessageBoxExternal("CashBack.html", 'N', null, null, 820, 'Information', 670);
    else
        SelectTab(6, 6);
}

function NewUserEmail()
{
    MightyPlace.WebServices.LoginService.SendNewUserEmail(NewUserEmailComplete, WebError);
}

function NewUserEmailComplete(results)
{
    window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    $get('hiddenWindowIntervalID').value = window.setInterval("ResetSession();", 900000); //15 minutes    
    if (results == 0)
        MessageBox("<br />An email has just been sent containing an activation link that you must click on to activate your account.<br />", 'N', null, null, 550, null, 70);
    else
        MessageBox("There was an error sending the email.<br /><br />Contact CustomerService@MightyPlace.com for more information.<br />", 'Y'); 
}

function ContactUs() 
{
    ShowWaitDialog();
    MessageBoxExternal("ContactUs.html", 'N', null, null, 900, 'Contact Us', 500);
}

function AdvertiseWithUs() 
{
    ShowWaitDialog();
    MessageBoxExternal("Advertising.html", 'N', null, null, 1100, 'Advertise With Us');
}

function AboutUs() 
{
    ShowWaitDialog();
    MessageBoxExternal("AboutUs.html", 'N', null, null, 1100, 'About Us');
}

function Privacy() 
{
    ShowWaitDialog();
    MessageBoxExternal("PrivacyPolicy.html", 'N', null, null, 1100, 'Privacy Policy');
}

function TermsOfService() 
{
    ShowWaitDialog();
    MessageBoxExternal("TermsOfService.html", 'N', null, null, 1100, 'Terms Of Service');
}

function FixAds(Override, adcnt) 
{
    $get('divAdsMain').style.display = 'none';
    var tab = $get('hiddenTab').value;
    if (tab == '6' || tab == '5') 
    {
        if (Override == null) 
        {
            $get('divAdsMain').style.display = 'none';
            return;
        }
    }
    if (adcnt == null) 
    {
        var x = Math.round($get('tdBodyMain').clientHeight / 145);
        if (x > 10)
            x = 10;
    }
    else
        x = adcnt;
    MightyPlace.WebServices.CommonService.GetRandomAds(x, GetRandomAdsComplete, WebError);        
}

function GetRandomAdsComplete(results)
{
    if (results.length > 0) 
    {
         $get('divAdsMain').innerHTML = results;
        $get('divAdsMain').style.display = 'block';
    }
    else
        $get('divAdsMain').style.display = 'none';
    GetMasterFeeds();
}

function ClickAd(adid, url) 
{
    //save ad click event
    window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    $get('hiddenWindowIntervalID').value = window.setInterval("ResetSession();", 900000); //15 minutes    
    MightyPlace.WebServices.CommonService.SaveNewAdClick($get('hiddenUser_ID').value, adid);
    if (navigator.appVersion.indexOf('Chrome') > 0)
        window.location = url;
    else
        window.open(url);
}

function CreateBookMark(title, url) 
{
    if (window.sidebar) { // Mozilla Firefox Bookmark		
        window.sidebar.addPanel(title, url, "");
    }
    else if (window.external) { // IE Favorite		
        window.external.AddFavorite(url, title);
    }
    else if (window.opera && window.print) { // Opera Hotlist		
        return true;
    }
}

function OpenReward(merchantid) 
{
    window.location.href = "http://" + window.location.host + "/Shopping/CreateReward.aspx?m=" + merchantid;
}

function OpenMerchant(merchantid, pageurl) 
{
    $get('hiddenSelectedMerchant_ID').value = merchantid;
    ShowWaitDialog();
    
    if (pageurl.length > 0)
        window.location = pageurl;
    else
        MightyPlace.WebServices.ShoppingService.GetMerchant(merchantid, OpenMerchComplete, WebError);
}

function OpenMerchComplete(results) 
{
    window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    $get('hiddenWindowIntervalID').value = window.setInterval("ResetSession();", 900000); //15 minutes    
    $get('imgShopMerchant').src = '';
    $get('imgShopMerchant').src = results.GraphicURL;
    $get('imgShopMerchant').alt = results.MerchantName;
    $get('imgshopname').innerHTML = results.MerchantName + "<br /><div style='width:800px; color:red; text-align:center;'>Reward: " + results.CashBack + "</div>";

    var msg = "";
    if ($get('hiddenUser_ID').value == '0')
        msg = "<span style='color:red; font-size:larger;'>WARNING: You are not currently logged in and will not earn reward credit for any purchases made.</span><br><br>";
    msg += "<div style='color:navy; text-align:center;'>" + results.ExtendedMDescription + "</div><br /><hr class='blue-line'/>";
    msg += "Here is a link that you can give to friends and family for this merchant that will give you full reward credit for any purchases they make. ";
    msg += "In addition, you can also add this to your favorites by clicking here: <input type='button' style='vertical-align:bottom' id='btnAddToFavorites' onclick=\"CreateBookMark('MightyPlace.com - " + results.MerchantName + "','/shopnow.aspx?m=" + results.Merchant_ID + "&u=" + $get('hiddenUser_ID').value;
    msg += "');\" class='button btn-createbookmark'/> (Not available on Chrome).<br><br>Link: "
    msg += "<span style='width:800px; text-align:center;'>&nbsp;<input id='shopurl' type='text' readonly='readonly' style='width:600px; color:navy;' value='www.mightyplace.com/shopnow.aspx?m=";
    msg += results.Merchant_ID + "&u=" + $get('hiddenUser_ID').value + "'</input></span>";
    $get('divShopMerchantMessage').innerHTML = msg;
    $('#divPleaseWait').dialog('close');
    $get('btnShowMessageShop').click();
    
    //$('#divShopMerchant').dialog({ modal: true, title: 'Shopping - ' + results.MerchantName, draggable: true, resizable: false, show: 'Transfer', hide: 'Transfer', height: 'auto', width: '800px', position: 'center' });
}

function GetShoppingInfo() 
{
    ShowWaitDialog();
    MightyPlace.WebServices.CommonService.SaveMerchantClick($get('hiddenUser_ID').value, $get('hiddenSelectedMerchant_ID').value, SaveNewTranComplete, WebError);
}

function SaveNewTranComplete(results) 
{
    window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    $get('hiddenWindowIntervalID').value = window.setInterval("ResetSession();", 900000); //15 minutes    
    $.fn.colorbox.close();
    $('#divPleaseWait').dialog('close');
    if (results[0] == 0) 
    {
        if (navigator.appVersion.indexOf('Chrome') > 0)
            window.location = results[1];
        else
            window.open(results[1]);
    }
    else
        MessageBox('There is an error connecting to this merchant.  The System Administrator has been notified. Please try again later.  Sorry for the inconvenience.<br />', 'Y');
}

function LoadDefault() 
{
    MightyPlace.WebServices.ShoppingService.GetLatestMerchants(GetLatestMerchantsCompleteMain, WebError);
}

function GetLatestMerchantsCompleteMain(results) 
{
    window.clearInterval($get('hiddenWindowIntervalID').value);  //user is not logged in, clear interval..
    $get('hiddenWindowIntervalID').value = window.setInterval("ResetSession();", 900000); //15 minutes    
    if (results[0].length > 0) 
        $get('divRMerchants').innerHTML = results[0];
    //if (results[2].length > 0) 
    //    $get('divRRewards').innerHTML = results[2];

    $('#txtSearchMerchants').keypress(function(e) {
        if (e.which == 13) {
            e.which = 0;
            SearchMerchants(null, null, 0);
            return false;
        }
    });

    $get('divNew').style.display = 'block';
    // JCarousel LITE
    $(".jcarouselprev").jCarouselLite
    ({
        scroll: 1,
        speed: 2000,
        visible: 1,
        vertical: true,
        auto: 5000
        
        //btnPrev: ".prevfeat",
        //btnNext: ".nextfeat"
    });

    $get('divFeatured').style.display = 'block';
    // JCarousel LITE
    $(".jcarouselFeatured").jCarouselLite
    ({
        scroll: 1,
        speed: 2000,
        visible: 5,
        auto: 2500
        
//        //btnPrev: ".prevsel",
//        //btnNext: ".nextsel"
    });
    $('#divPleaseWait').dialog('close');  
}

function OpenRwd(rowid) 
{
    ShowWaitDialog();
    OpenReward($get('rwdid' + rowid).value);
}

function ShopCategory(categoryid) 
{
    window.location.href = "http://" + window.location.host + "/Shopping.aspx?cs=" + categoryid;
}

function ShowWaitDialog() 
{
    $('#divPleaseWait').dialog({ modal: true, title: "Please Wait...", closeOnEscape: false, draggable: false, resizable: false, height: 'auto', width: '200', position: 'center',
        open: function (event, ui) { $(".ui-dialog-titlebar-close").hide(); }
    });
}

