﻿function $(element) {
    return document.getElementById(element);
}

//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;
}

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";
            
            $('userName').innerHTML = result.Data[0];
            $('creditsLeft').innerHTML = result.Data[1];
            
            refreshCart();

        }
    }
    
    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";
            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)
{
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        if (result.Status == 1) {
            refreshCart();
            document.location = result.RedirectUrl;
            
        } 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);
        }
    }
    
    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 addToCart(itemId, amount)
{
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        refreshCart();
    }
    
    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()
{
    //remove the class
    var re = /cartAdded/gi;
    document.documentElement.className = document.documentElement.className.replace(re, "");
}
function showCartHasItems()
{
    $("viewCart").style.display = "block";
    if (document.documentElement.className.indexOf("cartAdded") == -1) {
        document.documentElement.className = document.documentElement.className + " cartAdded";
    }
}

//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
var cartUpdateListeners = new Array();
function refreshCart()
{
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        var items = result.Data.Items;
        var cartDropDown = $("cartItems");
        if (items != null && items.length > 0) {
            cartDropDown.length = 0;
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                cartDropDown.options[cartDropDown.length] = new Option(item.Name,item.Id)
            }
            $("cartTotalSum").innerHTML = result.Data.TotalSum;
            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);}
}

function playsound(soundId, loopcount) 
{
    try {   
        if (frames.player) {
            frames.player.document.location = '/playsound.aspx?soundurl=http://www.powerfx.com/getsound/' + soundId + '.mp3';
        }
    }
    catch (e) {alert(e);return false;}
}

function stopsound() 
{
    try {   
    	frames.player.document.location = 'blank.htm';
    }
    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, subscribe) {
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        if (result.Message != "") {
            myalert(result.Message);
        }
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.NewsletterSignUp(email, 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);}
}

//a standard call back wrapper which can be used whenever a standard callback function shall be used
function standardCallback(finalCallback) 
{
    function innerStandardCallback(ajaxResult) {
        var result = ajaxErrorHandler(ajaxResult);
        finalCallback(result);
        if (result.Message != "" && result.Message != null) {
            myalert(result.Message);
        }
        if (result.RedirectUrl != "" && result.RedirectUrl != null) {
            document.location = result.RedirectUrl;
        } else if (result.ReloadPage) {
            document.location.reload();
        }
    }
    return innerStandardCallback;
}

function createUser(email, newsletter)
{
    function callback(result)
    {
    }
    
    try {
        Iteam.Trex.Web.Site.Backend.CreateUser(email, newsletter, 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);}
}

