﻿var err = "";
var err_msg = "";
var productName = "";
var productCount = 0;
var totalItems = 0;
var doTableInsert = true;
var msgRowID = "msgRow";
var msgLayerID = "msgLayer";
var persistantMsgLayer = true;
var eventSource = null;
var eventArg = null;
var progressPanel = null;

// ### document onload event ###
$(document).ready(function() {
    // #### addToCart buttons' click events ####
    $('input.addToCart').click(function() {
        eventArg = $(this).attr("data");
    });

    $('a.addToCart').click(function() {
        eventArg = $(this).attr("data");
    });
});

// #### helper method ####
function AddSlide(rowID, msgPanelID) {
    // create new panel and attached to the row
    var msgPanel = $('#' + msgRowID).clone(true);
    $(msgPanel).attr('id', msgPanelID);

    //$('#row'+rowID).after($('#'+msgRowID));
    $('#row' + rowID).after(msgPanel);
    //$('#'+msgRowID).show();
    $(msgPanel).show();

    return $(msgPanel);
}

function AddItemComplete() {
    if (err == "") {
        if ($('#' + msgLayerID) != undefined) {
            var msgPanel;
            if (doTableInsert) {
                if ($('#' + msgRowID) != undefined) {
                    //find current row, then append msg panel after this
                    //alert($(this).attr("data"));
                    var rowID = eventArg;
                    var msgPanelID = msgRowID + '_' + rowID;

                    // is msg layer persistant on the page?
                    if (persistantMsgLayer) {
                        // first check if msg row is already visible? and has same ID?
                        if ($("tr[id*='msgRow_']").length > 0) {
                            // we have one msgPanel on the form, check if this is same panel we want to use? 
                            if ($("tr[id*='msgRow_']")[0].id == msgPanelID) {
                                // yes, then do not do anything
                            } else {
                                // remove this from the page
                                $("tr[id*='msgRow_']").remove();

                                // add new panel
                                AddSlide(rowID, msgPanelID);
                            }
                        }
                        else {
                            // create new panel and attached to the row
                            AddSlide(rowID, msgPanelID);
                        }
                    } else {
                        // create new panel and attached to the row
                        msgPanel = AddSlide(rowID, msgPanelID);
                    }
                }
            }

            // find total items bit and replace with total items
            if ($('.currentTotalItems') != undefined)
                $('.currentTotalItems').html(totalItems + ' item(s)');

            //            if($('.currentTotalItems')!=undefined)
            //            {
            //                $('.currentTotalItems').html(totalItems + ' item(s)');
            //                $('.currentTotalItems').animate({fontSize: "100%"}, 1000,"swing",function(){
            //                    $('.currentTotalItems').animate({fontSize: "100%"}, 500);
            //                });
            //            }

            // find template variables and update with current product name
            if ($('#' + msgRowID + '_' + rowID + ' #productName') != undefined) {
                if ($('#' + msgRowID + '_' + rowID + ' #productName').text().indexOf('{productName}') > -1) {
                    $('#' + msgRowID + '_' + rowID + ' #productName').text($('#' + msgRowID + '_' + rowID + ' #productName').text().replace(/\{productName\}/gim, productName));
                }
            }

            // find quantity span element and update it with current quantity
            if ($('#' + msgRowID + '_' + rowID + ' #productQuantity') != undefined) {
                $('#' + msgRowID + '_' + rowID + ' #productQuantity').html('&nbsp;x&nbsp;<strong>' + productCount + '</strong>');
                $('#' + msgRowID + '_' + rowID + ' #productQuantity').animate({ fontSize: "18pt" }, 500, "swing", function() {
                    $('#' + msgRowID + '_' + rowID + ' #productQuantity').animate({ fontSize: "10pt" }, 500);
                });
            }

            // is persistant layer?
            if (!persistantMsgLayer) {
                // if not, show and hide this from the page on intervals
                $('#' + msgRowID + '_' + rowID + ' #' + msgLayerID).slideToggle("slow", function() {
                    setTimeout(function() {
                        $('#' + msgRowID + '_' + rowID + ' #' + msgLayerID).slideToggle("slow", function() {
                            if (doTableInsert) {
                                if ($(msgPanel) != undefined) {
                                    // TO DO 
                                    $(msgPanel).hide();
                                    $(msgPanel).remove();
                                }
                            }
                        });
                    }, 3000);
                });
            } else {
                // is this already shown?
                if (!$('#' + msgRowID + '_' + rowID + ' #' + msgLayerID).is(':visible')) {
                    // if not, the slide this out
                    $('#' + msgRowID + '_' + rowID + ' #' + msgLayerID).slideDown("slow");
                }
            }
        }
    };
}

function continueAddSHOWStudioToCart(name, productId, variationId, qnt, promo, panelId){
    productName = name;

    if (panelId) {
        progressPanel = $('#' + panelId);
    }

    if (progressPanel)
        progressPanel.show();

    OrderWebService.AddShowStudioToBasket(productId, variationId, qnt, promo, function(res) {
        err = parseAddItemToBasketResponse(res);
        // callback function
        AddItemComplete();
          if (progressPanel)
            progressPanel.hide();
    }, function(error) {
        err_msg = error.get_message();
        err = parseAddItemToBasketResponse("ERROR:Item cannot be added to basket. " + err_msg);
        // callback function
        AddItemComplete();
        if (progressPanel)
            progressPanel.hide();
    });
}
function addSHOWStudioToCart(name, productId, variationId, qnt, promo, panelId) {
    qnt = $("#" + qnt).val();
    promo = $("#" + promo).val();

    if (isNaN(qnt) || Number(qnt) < 1) {
        alert("Please select at least 1 quantity to add to cart.");
        return false;
    }

    /// start : somerset specific check
    if (variationId.indexOf("|") > 0) {
        var dataItems = variationId.split("|")
        productId = dataItems[1];
        variationId = dataItems[0];
        if (dataItems.length > 1) {
            productName = dataItems[2];
        }
    } else {
        variationId = variationId + 0;
    }
    /// end : somerset specific check

    if (promo != "")
    {
      OrderWebService.CanApplyPromoCode(productId, variationId, qnt, promo, 
        function(r)
        {
          if (r == true)
          {
            var confirmText = "You have added {TicketsAdded} ticket{TicketPlural}. This is a 2 for 1 promotion so {TotalTickets} tickets will be added to your basket and you will be charged for {TicketsAdded}. Is this correct? Click OK or click cancel to change the quantity.";
            confirmText = confirmText.replace("{TicketsAdded}", qnt.toString());
            confirmText = confirmText.replace("{TicketsAdded}", qnt.toString());
            confirmText = confirmText.replace("{TotalTickets}", (qnt * 2));
           
            if (qnt > 1)
            {
              confirmText = confirmText.replace("{TicketPlural}","s");
            }
            else
            {
              confirmText = confirmText.replace("{TicketPlural}","");
            }
          
            confirmText = confirmText.replace("{TotalTickets}", qnt.toString());
          
            var confirmResult = confirm(confirmText);
            if (confirmResult)
            {
              continueAddSHOWStudioToCart(name, productId, variationId, qnt, promo, panelId);
            }
            else
            {
              return;            
            }
          }
          else
          {
            continueAddSHOWStudioToCart(name, productId, variationId, qnt, promo, panelId);
          }
        }
        ,
        function(e)
        { }
      );  
    }
    else
    {
      continueAddSHOWStudioToCart(name, productId, variationId, qnt, promo, panelId);
    }
}

function addSimpleToCart(name, productId, variationId, qnt) {
    qnt = $("#" + qnt).val();
    productName = name;

    if (isNaN(qnt) || Number(qnt) < 1) {
        alert("Please select at least 1 quantity to add to cart.");
        return false;
    }
    
    addToCart(productId, variationId, name, Number(qnt));
    return false;
};

function addToCart(productId, variationId, name, quantity) {
    OrderWebService.AddItemToBasket(productId, variationId, quantity, function(res) {
        err = parseAddItemToBasketResponse(res);
        // callback function
        AddItemComplete();

    }, function(error) {
        err_msg = error.get_message();
        err = parseAddItemToBasketResponse("ERROR:Item cannot be added to basket. " + err_msg);
        // callback function
        AddItemComplete();
    });

    if (progressPanel)
       progressPanel.hide();
};
function parseAddItemToBasketResponse(res) {

    if (res.indexOf("ERROR:") != -1) {
        alert(res.replace("ERROR:", ""));
        return true;
    } else {
        res = res.replace("OK:", "");
        productCount = res.split("|")[1];
        totalItems = res.split("|")[0];
        return false;
    }
}
function OnlyNumeric(e) {
    if ([e.keyCode || e.which] == 8) //this is to allow backspace
        return true;
    if ([e.keyCode || e.which] < 48 || [e.keyCode || e.which] > 57)
        e.preventDefault ? e.preventDefault() : e.returnValue = false;
}
var dropDownIdCurrent = null;
var dropDownSpeed = "fast";
var imageCrossFadeSpeed = "normal";

function dropDownSelect(name, url, dropDownId) {
    $("#dropDownSelected_" + dropDownId).get(0).innerHTML = name;
    eval(dropDownId + " = url");
    dropDownClose(dropDownId);
}

function dropDownToggle(dropDownId) {
    if (dropDownId == dropDownIdCurrent) {
        dropDownClose(dropDownId);
        return;
    }
    if ((dropDownIdCurrent != null)) {
        dropDownClose(dropDownIdCurrent);
    }
    dropDownOpen(dropDownId);
}

function dropDownOpen(dropDownId) {
    $("#dropDown_" + dropDownId).slideDown(dropDownSpeed);
    dropDownIdCurrent = dropDownId;
}

function dropDownClose(dropDownId) {
    $("#dropDown_" + dropDownId).slideUp(dropDownSpeed);
    dropDownIdCurrent = null;
}

function dropDownNavigate(dropDownId) {
    window.location = eval(dropDownId);
}

function imageLoad() {
    $(this).fadeIn(imageCrossFadeSpeed);
    $(this).unbind("load", imageLoad);
}

function swapImage(placeHolder, imageUrl) {
    if ($("#" + placeHolder)[0].src != imageUrl) {
        $("#" + placeHolder).fadeOut(imageCrossFadeSpeed, function() {
            $(this).load(imageLoad);
            this.src = imageUrl;
        });
    }
};

function modalPopupOpen(popupId) {
    $("#" + popupId).show();
}

function modalPopupClose(popupId) {
    $("#" + popupId).hide();
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}