﻿//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";
            $('loginBox').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();
            //alert("Your selection has been added to your shopping cart - click on the Checkout button at the bottom of the page to complete your purchase."); //we need to notify the user somehow
            buyElement.className = "button 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);
        }
    }
    
    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();
        if (result.Data > 0) {
        } else {
            alert(result.Message);
        }
    }
    
    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()
{   
    $("checkOut").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
//if (typeof cartUpdateListeners == "undefined") {
//    cartUpdateListeners = new Array();
//}

function refreshCart()
{
    function callback(ajaxResult)
    {
        var result = ajaxErrorHandler(ajaxResult);
        var items = result.Data.Items;
      //  var cartDropDown = $("cartItems");
        //Show the cart and fixate it
       document.body.className+=" cartAdded";
        $("cart").style.display="block";
        
       // cartDropDown.length = 0;
        $("cartTotalSum").innerHTML = result.Data.TotalSum + ".00 USD";
        var soundCount = 0;
        var soundTotalSum = 0;
        var cdCount = 0;
        var cdTotalSum = 0;
        for (var i = 0; i < items.length; i++) {
                var item = items[i];
                //CD
                if (item.Type == 1 || item.Type == 14) {
                    cdCount++;
                    cdTotalSum += item.CalculatedPrice;
                } else {
                    soundCount++;
                    soundTotalSum += item.CalculatedPrice;
                }
            }

            $("cartSoundCount").innerHTML = soundCount;
            $("cartSoundsSum").innerHTML = soundTotalSum + ".00 USD";
            $("cartCDCount").innerHTML = cdCount;
            $("cartCDSum").innerHTML = cdTotalSum + ".00 USD";
            if (soundCount > 0)
                $("cartSounds").style.display = "block";
            else
                $("cartSounds").style.display = "none";

            if (cdCount > 0)
                $("cartCDs").style.display = "block";
            else
                $("cartCDs").style.display = "none";
                
//        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 setLastPlayedSoundId(soundId)
{
    lastPlayedSoundId = soundId;
}

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 {
        document.body.className += " cartAdded"; //Makes the flash fixed to the screen
        $('flashPlayer').style.display = 'block';
        var playButton = $('play' + soundId);
        resetPlayButton();
        playSound_impl('/getsound/' + soundId + '.16', playButton);
        setCurrentSound(soundId);
        lastPlayedSoundId = soundId;
        var stopButton = $('stop' + soundId);
        $('buyCurrentTrack').className = 'button';
        $('boughtCurrentTrack').className = 'button';
        $('downloadCurrentTrack').className = 'button';
        if (typeof stopButton != null) {
            if (typeof playButton != null) {
                stopButton.style["display"] = "block";
                playButton.style["display"] = "none";
            }
        }
        
        window.setTimeout(function(){
            set_titles(soundId);
            setButton(playButton);
        }, 200);
    }
    catch (e) { 
        // alert(e); 
        return false; 
    }
}
function setButton(playbutton) {
    var className = playbutton.className;
    if (className.indexOf("Download") != -1) {
        if(document.getElementById("downloadCurrentTrack"))
        {
        document.getElementById("downloadCurrentTrack").style.visibility = "visible";
        document.getElementById("boughtCurrentTrack").style.visibility = "hidden";
        document.getElementById("buyCurrentTrack").style.visibility = "hidden";
        }
    }
    else if (className.indexOf("Buy") != -1) {
    document.getElementById("buyCurrentTrack").style.visibility = "visible";
    document.getElementById("downloadCurrentTrack").style.visibility = "hidden";
    document.getElementById("boughtCurrentTrack").style.visibility = "hidden";
    }
    else if (className.indexOf("Disabled") != -1) {
    document.getElementById("boughtCurrentTrack").style.visibility = "visible";
    document.getElementById("downloadCurrentTrack").style.visibility = "hidden";
    document.getElementById("buyCurrentTrack").style.visibility = "hidden";
    }
}

//Set text for title field. Searches result grid DOM for correct values.
function set_titles(currentSound) {
    var titleText = document.getElementById("name" + currentSound).childNodes[0].nodeValue;
    var lengthText = "";
 
    if (document.getElementById("time" + currentSound)) {
            lengthText = "Length: " + document.getElementById("time" + currentSound).innerHTML;
        }

    document.getElementById("trackName").innerHTML = titleText; 
    document.getElementById("length").innerHTML = lengthText;
}

//New stopsound function. Copied from Westar.
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);}
}

//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) {
                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);}
}

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);}
}