﻿
//allows you to do a C# format on javascript strings
String.prototype.format = function()
{
    var str = this;
    for(var i=0;i<arguments.length;i++)
    {
        var re = new RegExp('\\{' + (i) + '\\}','gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}

function ajaxErrorHandler(ajaxResult)
{
    try {
        if (ajaxResult.error)
        {
	        myalert("An error occurred\r\n" + ajaxResult.error.Message);
	        return null;
        }
        else return ajaxResult.value;
    } catch (e)
    {
        myalert('Error in errorhandler, err' + e.message);
    }
}        

function handleError(e)
{
    myalert(e);
    return false;
}

//a standard call back wrapper which can be used whenever a standard callback function shall be used
function standardCallback(finalCallback, errorCallback) {
    function innerStandardCallback(ajaxResult) {
        var result = ajaxErrorHandler(ajaxResult);
        if (result == null && typeof (errorCallback) != "nothing") {
            errorCallback();
        } else {
            if (typeof (finalCallback) != "nothing") {
                finalCallback(result);
            }
            if (result.Message != "" && result.Message != null) {
                if (result.ReloadPage || result.RedirectUrl)
                    alert(result.Message); // use the system alert so we can wait until the OK is pressed before reloading the page.
                else
                    myalert(result.Message);
            }
            if (result.RedirectUrl != "" && result.RedirectUrl != null) {
                document.location = result.RedirectUrl;
            } else if (result.ReloadPage) {
                document.location.reload();
            }
        }
    }
    return innerStandardCallback;
}


//function standardCallback(ajaxResult)
//{
//    var result = ajaxErrorHandler(ajaxResult);
//    if (result.Message != "") {
//        myalert(result.Message);
//    }
//}

function doLogin()
{
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        if (result.Status == 1) {
            $('notLoggedIn').style.display = "none";
            $('loggedIn').style.display = "block";
            if (document.documentElement.className.indexOf("loggedIn") == -1) {
                document.documentElement.className = document.documentElement.className + " loggedIn";
            }
            
            $('userName').innerHTML = result.Data[0];
            //$('creditsLeft').innerHTML = result.Data[1];
            
            refreshCart();

        } else {
            alert(result.Message);
        }
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.Login($('email').value, $('password').value, $('saveCheckbox').checked, callback)
    } catch (e) {return handleError(e);}
    
}

function doLogout()
{
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        if (result.Status == 1) {
            $('notLoggedIn').style.display = "block";
            $('loggedIn').style.display = "none";
            //remove the class
            var re = /loggedIn/gi;
            document.documentElement.className = document.documentElement.className.replace(re, "");
            
            refreshCart();
        }
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.Logout(callback)
    } catch (e) {return handleError(e);}
    
}

function downloadProduct(productDownloadId)
{
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        if (result.Status == 1) {
            document.location = result.RedirectUrl;
        } else {
            myalert(result.Message);
        }
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.DownloadProduct(productDownloadId, callback)
    } catch (e) {return handleError(e);}
}

function purchaseSound(soundId, buyElement) {
    var theBuyElement = buyElement;
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        if (result.Status == 1) {
            refreshCart();
            notify("Your selection has been added to your shopping cart - click on the Checkout button at the top of the page to complete your purchase."); //we need to notify the user somehow
            buyElement.className = "buy_disabled";
        } else {
            if (result.Status == 2)
            {
                var singleCreditsProductId = result.Data[0];
                var price = result.Data[1];
                if (confirm(result.Message + ". Do you want to buy credits now?"))
                {
                    addToCart(singleCreditsProductId, price);
                    setTimeout(function() {document.location.href = "~/home/personal/mycart?soundId=" + soundId + "&returnUrl=search.aspx?return=true";}, 1000);
                }
            }
            else
                myalert(result.Message);
        }
    }

    highlightShoppingCartAddition(theBuyElement);
    
    try {
        Iteam.Trex.Web.Site.Backend.PurchaseSound(soundId, callback)
    } catch (e) {return handleError(e);}
}

function sendSound(soundId, phoneNumber)
{
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        if (result.Status == 2) {
            var singleCreditsProductId = result.Data[0];
            var price = result.Data[1];
            if (confirm(result.Message + ". Do you want to buy credits now?"))
            {
                addToCart(singleCreditsProductId, price); 
                setTimeout(function() {document.location.href = "~/home/personal/mycart?returnUrl=" + document.location.href + "?return=true";}, 1000);
            }
        } else {
            myalert(result.Message);
        }
    }

    try {
        phoneNumber = prompt('Enter the phone number you want to send the sound to', phoneNumber);
        Iteam.Trex.Web.Site.Backend.SendSound(soundId, phoneNumber, callback)
    } catch (e) {return handleError(e);}
}

function saveSound(soundId, doSave)
{
    try {
        Iteam.Trex.Web.Site.Backend.SaveSound(soundId, doSave)
    } catch (e) {return handleError(e);}
}

function highlightShoppingCartAddition(element) {

    if (element != null) {
        var cartWrapper = Ext.fly('shoppingCartWrapper');
        var x = cartWrapper.getX();
        var y = cartWrapper.getY();
        Ext.fly(element.appendChild(element.cloneNode(true))).shift({ x: x, y: y, callback: function(element) { Ext.fly('shoppingCartWrapper').frame(); } }).puff({ remove: true });
    }
}

function notify(message) {
    Ext.fly("MyDialog").update(message).fadeIn().pause(5).fadeOut();
}


function addToCart(itemId, amount, element)
{
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        refreshCart();

        if (result.Data > 0) {
            notify("Your selection has been added to your shopping cart - click on the Checkout button at the top of the page to complete your purchase.");
        } else {
            Ext.Msg.alert("A problem occurred", result.Message);
        }
    }

    highlightShoppingCartAddition(element);
    
    
    try {
        Iteam.Trex.Web.Site.Backend.AddToCart(itemId, amount, callback)
    } catch (e) { return handleError(e); }
}

function alterCartItem(cartItemId, amount)
{
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        refreshCart();
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.AlterCartItem(cartItemId, amount, callback)
    } catch (e) {return handleError(e);}
}

//these two methods can be overridden in other code to prevent the class of the document to be changed
function showCartEmpty()
{
}
function showCartHasItems()
{   
    $("checkOut").style.display = "block";
}

//all functions in this array will be called when the cart is updated
//this can be used for automatic updating of the page, such as on ShoppingCart.aspx
//if (typeof cartUpdateListeners == "undefined") {
//    cartUpdateListeners = new Array();
//}

function refreshCart()
{
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        var items = result.Data.Items;
        var cartDropDown = $("cartItems");
        cartDropDown.length = 0;
        $("cartTotalSum").innerHTML = result.Data.TotalSum + " USD";
        if (items != null && items.length > 0) {
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                cartDropDown.options[cartDropDown.length] = new Option(item.Name,item.Id)
            }
            showCartHasItems();
        } else {
            showCartEmpty();
        }
        
        for (var i = 0; i < cartUpdateListeners.length; ++i) {
            cartUpdateListeners[i](result.Data);
        }
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.GetCart(callback)
    } catch (e) {return handleError(e);}
}

var lastPlayedSoundId;
function resetPlayButton()
{
    var stopButton = $('stop' + lastPlayedSoundId);
    if (stopButton != null) {
        var playButton = $('play' + lastPlayedSoundId);
        if (playButton != null) {
            stopButton.style["display"] = "none";
            playButton.style["display"] = "block";
        }
    }
}

function playsound(soundId, loopcount, element) 
{
    try {
        var playButton = $('play' + soundId);
        resetPlayButton();
        playSound_impl('http://new.westarmusic.com/getsound/' + soundId + '.mp3', playButton);
        lastPlayedSoundId = soundId;
        var stopButton = $('stop' + soundId);
        if (typeof stopButton != null) {
            if (typeof playButton != null) {
                stopButton.style["display"] = "block";
                playButton.style["display"] = "none";
            }
        }
    }
    catch (e) {alert(e);return false;}
}

function stopsound() 
{
    try {   
        resetPlayButton();
        stopSound_impl();
    }
    catch (e) {alert(e); return false;}
}

//kept for compatability with 2.6
function openAWindow(url,title, w, h, center) {
    return openWindow(url, title, w, h, center);
}


//reports a support issue
function reportSupportIssue(email, subject, message) {
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        if (result.Message != "") {
            myalert(result.Message);
        }
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.ReportSupportIssue(email, subject, message, callback)
    } catch (e) {return handleError(e);}
}

function newsletterSignUp(email, fullName, subscribe) {
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        if (result.Message != "") {
            myalert(result.Message);
        }
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.NewsletterSignUp(email, fullName, subscribe, callback)
    } catch (e) {return handleError(e);}
}

function lostPassword(email) {
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        if (result.Message != "") {
            myalert(result.Message);
        }
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.LostPassword(email, callback)
    } catch (e) {return handleError(e);}
}

function changeCurrency(currencyId) {
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        if (result.Message != "") {
            myalert(result.Message);
        }
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.ChangeCurrency(currencyId, callback)
    } catch (e) {return handleError(e);}
}

function createUser(email, newsletter, name, companyName, street, city, state, countryId, zip, phone )
{
    function callback(result)
    {
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.CreateUser(email, newsletter, name, companyName, street, city, state, countryId, zip, phone, standardCallback(callback))
    } catch (e) {return handleError(e);}
}

function changePassword(newPassword, oldPassword)
{
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        if (result.Message != "") {
            myalert(result.Message);
        }
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.ChangePassword(newPassword, oldPassword, callback)
    } catch (e) {return handleError(e);}
}

function createPromoUser(email, promoCode)
{
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        if (result.Message != "") {
            myalert(result.Message);
        }
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.CreatePromoUser(email, promoCode, callback)
    } catch (e) {return handleError(e);}
}

function addUserPromotionCredits(email, promoCode)
{
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        if (result.Message != "") {
            myalert(result.Message);
        }
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.AddUserPromotionCredits(email, promoCode, callback)
    } catch (e) {return handleError(e);}
}

function saveSoundList(soundlistName, soundIds)
{
    try {
        Iteam.Trex.Web.Site.Backend.SaveSoundList(soundlistName, soundIds, standardCallback())
    } catch (e) {return handleError(e);}
}

function applyForOffer(discountOfferKey)
{
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        if (result.Message != "") {
            myalert(result.Message);
        }
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.ApplyForOffer(discountOfferKey, callback)
    } catch (e) {return handleError(e);}
}
