
// Begin GearsJS
GearsJS = {
    CartUpdate: function(item_no, qty) {
        $.ajax({
            type: "POST",
            url: "/Gears/MarketPlace/WebServices/MarketPlaceServices.asmx/UpdateCart",
            contentType: "application/json; charset=utf-8",
            data: "{ \"no\" : \"" + item_no + "\", \"qty\" : " + qty + "  }",
            dataType: "json",
            success: GearsJS.UpdateSuccess,
            error: GearsJS.UpdateFail
        });
    },
    CartRemove: function(item_no) {
        $.ajax({
            type: "POST",
            url: "/Gears/MarketPlace/WebServices/MarketPlaceServices.asmx/RemoveFromCart",
            contentType: "application/json; charset=utf-8",
            data: "{ \"no\" : \"" + item_no + "\"  }",
            dataType: "json",
            success: GearsJS.RemoveSuccess,
            error: GearsJS.RemoveFail
        });
    },
    CartAdd: function(item_no, item_qty) {
        $.ajax({
            type: "POST",
            url: "/Gears/MarketPlace/WebServices/MarketPlaceServices.asmx/AddToCart",
            contentType: "application/json; charset=utf-8",
            data: "{ \"no\" : \"" + item_no + "\", \"qty\" : " + item_qty + "  }",
            dataType: "json",
            success: GearsJS.AddSuccess,
            error: GearsJS.AddFail
        });
        

    },
    CartCampaignAdd: function(item_no, item_qty, campaigncode, horizontal, vertical, extra) { 
        $.ajax({
            type: "POST",
            url: "/Gears/MarketPlace/WebServices/MarketPlaceServices.asmx/AddToCartCampaign",
            contentType: "application/json; charset=utf-8",
            data: "{ \"no\" : \"" + item_no + "\", \"qty\" : " + item_qty + ", \"horizontal\" : \"" + horizontal + "\", \"vertical\" : \"" + vertical + "\", \"extra\" : \"" + extra + "\" , \"campaigncode\" : \"" + campaigncode + "\" }",
            dataType: "json",
            success: GearsJS.AddSuccess,
            error: GearsJS.AddFail
        });
    },
    RemoveSuccess: String,
    RemoveFail: String,
    AddSuccess: String,
    AddFail: String,
    UpdateSuccess: String,
    UpdateFail: String
}
// end GearsJS

// STATUS

function CheckIfCampaign(  ){
    return '';
}


function renderStatus(resultString, enum_statusType) {
        $("#marketplacestatus_inner").html(resultString);
        document.getElementById('marketplacestatus').className = enum_statusType;
        $("#marketplacestatus").stop().fadeTo('slow', 1).show();
}

function hideStatus() {
        $("#marketplacestatus").stop().fadeTo('fast', 1).hide();
}
// 

// Togglers
function toggleCart( ) {
        $("#shoppingCartWrapper").slideToggle('fast');
}


function hideWishList() {
        $("#wishListSelector").slideToggle('fast');
        // $("#wishListSelect").slideToggle('fast');
        // $("#wishListCreate").slideToggle('fast');
    }

// Wishlist

function AddToTemplate(item_no){
        //if (document.getElementById("sltAddToFavorite").options.length == 0 || document.getElementById("sltAddToFavorite").options[0].value == "---") {
            Gears.MarketPlace.WebServices.MarketPlaceServices.GetOrderTemplates(WLPopulate, WLFail);
        //}

        $("#wishlistQtyContainer").show();
        $("#hlWishlist").hide();
        $("#hlTemplate").show();

        $("#wishListSelector").slideToggle('fast');
        $("#wishListSelector").position({
            my: "left bottom",
            of: this,
            offset: "-50 -50",
            /*offset: "-100 -100",*/
            collision: "none"
        });
        document.getElementById("activeProductNo").value = item_no;
        document.getElementById("activeListType").value = 2;

}

function AddToWishlist(item_no) {
        //if (document.getElementById("sltAddToFavorite").options.length == 0 || document.getElementById("sltAddToFavorite").options[0].value == "---") {
            Gears.MarketPlace.WebServices.MarketPlaceServices.GetFavouriteLists(WLPopulate, WLFail);
        //}
        $("#wishlistQtyContainer").hide();
        $("#hlWishlist").show();
        $("#hlTemplate").hide();
        $("#wishListSelector").slideToggle('fast');
        $("#wishListSelector").position({
            my: "left bottom",
            of: this,
            offset: "-50 -50",
            /*offset: "-100 -100",*/
            collision: "none"
        });
        document.getElementById("activeProductNo").value = item_no;
        document.getElementById("activeListType").value = 1;
}

function AddToTemplate(item_no, variant){
        //if (document.getElementById("sltAddToFavorite").options.length == 0 || document.getElementById("sltAddToFavorite").options[0].value == "---") {
            Gears.MarketPlace.WebServices.MarketPlaceServices.GetOrderTemplates(WLPopulate, WLFail);
            if(variant != "")
            {
                Gears.MarketPlace.WebServices.MarketPlaceServices.GetVariants(item_no,VariantLPopulate, VariantLFail); 
                document.getElementById("divVariant").style.display = "";   
            }
            else
                document.getElementById("divVariant").style.display = "none";
            
        //}

        $("#wishlistQtyContainer").show();
        $("#hlWishlist").hide();
        $("#hlTemplate").show();

        $("#wishListSelector").slideToggle('fast');
        $("#wishListSelector").position({
            my: "left bottom",
            of: this,
            offset: "-50 -50",
            /*offset: "-100 -100",*/
            collision: "none"
        });
        document.getElementById("activeProductNo").value = item_no;
        document.getElementById("activeListType").value = 2;

}

function AddToWishlist(item_no, variant) {
        //if (document.getElementById("sltAddToFavorite").options.length == 0 || document.getElementById("sltAddToFavorite").options[0].value == "---") {
            Gears.MarketPlace.WebServices.MarketPlaceServices.GetFavouriteLists(WLPopulate, WLFail);
          if(variant != "")
          {
                Gears.MarketPlace.WebServices.MarketPlaceServices.GetVariants(item_no,VariantLPopulate, VariantLFail); 
                document.getElementById("divVariant").style.display = "";   
          } 
          else
                document.getElementById("divVariant").style.display = "none"; 
        //}
        $("#wishlistQtyContainer").hide();
        $("#hlWishlist").show();
        $("#hlTemplate").hide();
        $("#wishListSelector").slideToggle('fast');
        $("#wishListSelector").position({
            my: "left bottom",
            of: this,
            offset: "-50 -50",
            /*offset: "-100 -100",*/
            collision: "none"
        });
        document.getElementById("activeProductNo").value = item_no;
        document.getElementById("activeListType").value = 1;
}


function WLCreate() {
        //   $("#wishListSelect").fadeOut('fast');
        // $("#wishListCreate").slideToggle('fast');
}
function WLCreateList() {
        var list_name = document.getElementById('wishListNew').value;
        var list_type = document.getElementById('activeListType').value;
        
        if(!list_type) list_type = "2";
        var should_add_product = document.getElementById('also_add_to_list').checked;

        if (list_name == '') {
            var str = "List name can not be empty";  
            renderStatus(str, 'result_error');
            return;
        }
            Gears.MarketPlace.WebServices.MarketPlaceServices.CreateFavoriteList(list_name, list_type, OnCompleteCreateList, WLFail);
}
function WLAddToList() {
        elSelect = document.getElementById("sltAddToFavorite");
        var list_type = document.getElementById('activeListType').value;
        var qty = document.getElementById('wishlistQTY').value;
        if(!list_type) list_type = "2";

        if(elSelect.value == '---'){
          var str = "You have no lists! Create new list first, please";  
          renderStatus(str, 'result_error');
        } else {
        Gears.MarketPlace.WebServices.MarketPlaceServices.SaveToFavourite(elSelect.value, document.getElementById("activeProductNo").value, qty, OnCompleteSaveFavourite, WLFail);
        }
        document.getElementById('wishlistQTY').value = 0;
}


function WLPopulate(str) {
        if (str == "") {
            WLCreate();
        }
        if (str != "") {
            elSelect = document.getElementById("sltAddToFavorite");
            elSelect.options.length = 0;
            arr = str.split("###");
            for (var i = 0; i < arr.length; i++) {
                arr2 = arr[i].split(";;;");
                elSelect.options[elSelect.options.length] = new Option(arr2[1], arr2[0]);
            }
            //  $("#wishListCreate").fadeOut('fast');
            //  $("#wishListSelect").slideToggle('fast');
        }

    }
function WLFail(str) {
        alert('error:' + str);

}

function VariantLPopulate(str) {
        if (str == "") {
            WLCreate();
        }
        if (str != "") {
            elSelect = document.getElementById("sltVariantList");
            elSelect.options.length = 0;
            arr = str.split("###");
            for (var i = 0; i < arr.length; i++) {
                arr2 = arr[i].split(";;;");
                elSelect.options[elSelect.options.length] = new Option(arr2[1], arr2[0]);
                if(document.getElementById("activeProductNo").value == arr2[0])
                    elSelect.options[elSelect.options.length-1].selected = true;     
                
            }
            //  $("#wishListCreate").fadeOut('fast');
            //  $("#wishListSelect").slideToggle('fast');
        }

    }
function VariantLFail(str) {
        alert('error:' + str);

}

function OnCompleteGetFavouriteLists(str) {
        if (str != "") {
            elSelect = document.getElementById("sltAddToFavorite");
            arr = str.split("###");
            for (var i = 0; i < arr.length; i++) {
                arr2 = arr[i].split(";;;");
                elSelect.options[elSelect.options.length] = new Option(arr2[1], arr2[0]);
            }
            document.getElementById("divBox").style.display = "";
        }
        else {
            document.getElementById("divAlert").style.display = "";
        }
    }

    function OnTimeoutGetFavouriteLists() {
    }


function OnCompleteCreateList(result) {
        var should_add_product = document.getElementById('also_add_to_list').checked;
        
        var qty = document.getElementById('wishlistQTY').value;
        //alert(result);
        //
        if (result == 0) {
            var str = "Could not create list";  
            renderStatus(str, 'result_error');
        }
        if (result != 0 && should_add_product) {
            document.getElementById('wishListNew').value = '';
            Gears.MarketPlace.WebServices.MarketPlaceServices.SaveToFavourite(result, document.getElementById("activeProductNo").value, qty, OnCompleteSaveFavourite, WLFail);
        }
        if (!should_add_product) {
            // refresh dropdown
            var list_name = document.getElementById('wishListNew').value;
            document.getElementById("sltAddToFavorite").options.length = 0;
            Gears.MarketPlace.WebServices.MarketPlaceServices.GetFavouriteLists(WLPopulate, WLFail);
            
            var str = "List %1 created";  
            str = str.replace("%1", list_name);
            renderStatus(str, 'result_success');
        }
        document.getElementById('wishListNew').value = '';
    }
    function OnCompleteSaveFavourite(str) {
        //alert('saved!');
        //alert(str);

        var item_no = str.split('###')[1];
        var list_no = str.split('###')[0];
        var list_name = str.split('###')[2];
        $("#wishListSelector").slideToggle('fast');
        elSelect = document.getElementById("sltAddToFavorite").options.length = 0;
         //var status = 'Item \'' + item_no + '\' saved to list ' + list_name;
         str = "Item %1 saved to list %2";  
         str = str.replace("%1", item_no);
         str = str.replace("%2", list_name);
        var status = str;
        renderStatus(status, 'result_success');
    }

    function OnTimeoutSaveFavourite() {
    }
    
    
// QB

   function QuickBuyAddItem()
    {
        var itemNo = document.getElementById("textQuickBuyNo").value;
        var quantity = document.getElementById("textQuickBuyQuantity").value;
        
        if(itemNo == "")
        {
            document.getElementById("textQuickBuyNo").focus();
            return;
        }
        
        if((quantity=="") || isNaN(quantity))
        {
            document.getElementById("textQuickBuyQuantity").value = "";
            document.getElementById("textQuickBuyQuantity").focus();
            return;
        }
        
        if((itemNo != "") && (quantity!="") && (!isNaN(quantity)))
        {
            Gears.MarketPlace.WebServices.MarketPlaceServices.ExistItem(itemNo,OnCompleteQuickBuyExistItem,OnTimeoutQuickBuyExistItem);   
        }
    }
  
    function OnCompleteQuickBuyExistItem(status)
    {
        if(status == "yes"){
            var itemNo = document.getElementById("textQuickBuyNo").value;
            var quantity = document.getElementById("textQuickBuyQuantity").value;
            Gears.MarketPlace.WebServices.MarketPlaceServices.AddToCart(itemNo,quantity,OnCompleteQuickBuyAddToCart);
            }
        else
        {
            document.getElementById("textQuickBuyNo").value = "";
            document.getElementById("textQuickBuyQuantity").value = "";
            document.getElementById("textQuickBuyNo").focus();
            str = "Item doesn't exist";  
            renderStatus(str, 'result_warning');
        }
    }
    
    function OnTimeoutQuickBuyExistItem()
    {
        str = "Item doesn't exist";  
        renderStatus(str, 'result_warning');
    }
    
    function OnCompleteQuickBuyAddToCart()
    {
        
        try
        {
            str = "Adding Item %1 with quantity %2";
            str = str.replace("%1", document.getElementById("textQuickBuyNo").value);
            str = str.replace("%2", document.getElementById("textQuickBuyQuantity").value);
            renderStatus(str, 'result_success');
            renderMiniCart(null, false);
        }
        catch(e)
        {
        }
        document.getElementById("textQuickBuyNo").value = "";
        document.getElementById("textQuickBuyQuantity").value = "";
        document.getElementById("textQuickBuyNo").focus();
    }
    
     function checkEnter(e, posting_control) {
        var key;
        if (window.event)
            key = window.event.keyCode; //IE
        else
            key = e.which; //firefox
        //alert(key);

        if (key == 13) {
            document.getElementById(posting_control).click();
        }
        return (key != 13);
    }
    


   /* CAMPAIGN */

   function CheckCampaign() {
            $.ajax({
                type: "POST",
                url: "/Gears/MarketPlace/WebServices/MarketPlaceServices.asmx/GetCampaignInfo",
                contentType: "application/json; charset=utf-8",
                contentType: "application/json; charset=utf-8",
                data: "{}",
                dataType: "json",
                success: RenderCampaign,
                error: CampaignError
            });
        }
        var output = "";

        function RenderCampaign(result) {
            output = '';
            $('#camp').html('');
            var json = $.evalJSON(result.d);
            if (json.success) {
                for (var i = 0; i < json.data.Table.length; i++) {
                    var t = json.data.Table[i];
                    var _type = t.Type;
		var _css = "";
                    var _allowed = t.Allowed;
                    if (_allowed == "no") _css ="campaign_unreached";
                    if (_type == "Limit") {
                        if (i > 0) output += "</ul>";
                        output += "<h4 class=\"Campaignheadline "+ _css +"\"> Order $" + t.Limit + " + GST and receive   </h4><ul class=\"campaignlist "+ _css +"\">";
                    } else {
                        output += "<li class=\"campaignlistitem "+ _css +"\">";
                    }
                    if (_type == "Item") {
                        if (t.Used == "yes") {
                            output += "<i>" + t.QuantityUsed + " / " + t.Quantity + " "  + t.Description + "</i><br />";
                        } else {
                            output += "" + t.Quantity + " "  + t.Description + "<br />";
                        }
                    }
                    if (_type == "Category") {
                        if (t.Used == "yes") {
                            output += "<i>" + t.QuantityUsed + " / " + t.Quantity + " " + t.Description + "</i><br />";
                        } else {
                            output += "* " + t.Quantity + " " + t.Description + "<br />";
                        }

                    }

                    if (_type == "Variant") {
                        if (t.Used == "yes") {
                            output += "<i>" + t.QuantityUsed + " / " + t.Quantity + " " + t.Description + "</i><br />";
                        } else {
                            if( _allowed == "no" ){ 
				output += "" + t.Quantity + " " + t.Description + "<br />";
				} else {
				output += "* <a href='/Clubs/CampaignItems.aspx'>" + t.Quantity + " " + t.Description + "</a><br />";
				}
                        }
                    }
                    output += "</li>";
                }
            }
            $('#camp').html(output);
            $('#camp').slideToggle('fast');
        }
        function CampaignError(str) {
        }


    /**
    * jQuery JSON Plugin
    * version: 2.3 (2011-09-17)
    *
    * This document is licensed as free software under the terms of the
    * MIT License: http://www.opensource.org/licenses/mit-license.php
    *
    * Brantley Harris wrote this plugin. It is based somewhat on the JSON.org
    * website's http://www.json.org/json2.js, which proclaims:
    * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
    * I uphold.
    *
    * It is also influenced heavily by MochiKit's serializeJSON, which is
    * copyrighted 2005 by Bob Ippolito.
    */

    (function ($) {

        var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g,
		meta = {
		    '\b': '\\b',
		    '\t': '\\t',
		    '\n': '\\n',
		    '\f': '\\f',
		    '\r': '\\r',
		    '"': '\\"',
		    '\\': '\\\\'
		};

        /**
        * jQuery.toJSON
        * Converts the given argument into a JSON respresentation.
        *
        * @param o {Mixed} The json-serializble *thing* to be converted
        *
        * If an object has a toJSON prototype, that will be used to get the representation.
        * Non-integer/string keys are skipped in the object, as are keys that point to a
        * function.
        *
        */
        $.toJSON = typeof JSON === 'object' && JSON.stringify
		? JSON.stringify
		: function (o) {

		    if (o === null) {
		        return 'null';
		    }

		    var type = typeof o;

		    if (type === 'undefined') {
		        return undefined;
		    }
		    if (type === 'number' || type === 'boolean') {
		        return '' + o;
		    }
		    if (type === 'string') {
		        return $.quoteString(o);
		    }
		    if (type === 'object') {
		        if (typeof o.toJSON === 'function') {
		            return $.toJSON(o.toJSON());
		        }
		        if (o.constructor === Date) {
		            var month = o.getUTCMonth() + 1,
					day = o.getUTCDate(),
					year = o.getUTCFullYear(),
					hours = o.getUTCHours(),
					minutes = o.getUTCMinutes(),
					seconds = o.getUTCSeconds(),
					milli = o.getUTCMilliseconds();

		            if (month < 10) {
		                month = '0' + month;
		            }
		            if (day < 10) {
		                day = '0' + day;
		            }
		            if (hours < 10) {
		                hours = '0' + hours;
		            }
		            if (minutes < 10) {
		                minutes = '0' + minutes;
		            }
		            if (seconds < 10) {
		                seconds = '0' + seconds;
		            }
		            if (milli < 100) {
		                milli = '0' + milli;
		            }
		            if (milli < 10) {
		                milli = '0' + milli;
		            }
		            return '"' + year + '-' + month + '-' + day + 'T' +
					hours + ':' + minutes + ':' + seconds +
					'.' + milli + 'Z"';
		        }
		        if (o.constructor === Array) {
		            var ret = [];
		            for (var i = 0; i < o.length; i++) {
		                ret.push($.toJSON(o[i]) || 'null');
		            }
		            return '[' + ret.join(',') + ']';
		        }
		        var name,
				val,
				pairs = [];
		        for (var k in o) {
		            type = typeof k;
		            if (type === 'number') {
		                name = '"' + k + '"';
		            } else if (type === 'string') {
		                name = $.quoteString(k);
		            } else {
		                // Keys must be numerical or string. Skip others
		                continue;
		            }
		            type = typeof o[k];

		            if (type === 'function' || type === 'undefined') {
		                // Invalid values like these return undefined
		                // from toJSON, however those object members
		                // shouldn't be included in the JSON string at all.
		                continue;
		            }
		            val = $.toJSON(o[k]);
		            pairs.push(name + ':' + val);
		        }
		        return '{' + pairs.join(',') + '}';
		    }
		};

        /**
        * jQuery.evalJSON
        * Evaluates a given piece of json source.
        *
        * @param src {String}
        */
        $.evalJSON = typeof JSON === 'object' && JSON.parse
		? JSON.parse
		: function (src) {
		    return eval('(' + src + ')');
		};

        /**
        * jQuery.secureEvalJSON
        * Evals JSON in a way that is *more* secure.
        *
        * @param src {String}
        */
        $.secureEvalJSON = typeof JSON === 'object' && JSON.parse
		? JSON.parse
		: function (src) {

		    var filtered =
			src
			.replace(/\\["\\\/bfnrtu]/g, '@')
			.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
			.replace(/(?:^|:|,)(?:\s*\[)+/g, '');

		    if (/^[\],:{}\s]*$/.test(filtered)) {
		        return eval('(' + src + ')');
		    } else {
		        throw new SyntaxError('Error parsing JSON, source is not valid.');
		    }
		};

        /**
        * jQuery.quoteString
        * Returns a string-repr of a string, escaping quotes intelligently.
        * Mostly a support function for toJSON.
        * Examples:
        * >>> jQuery.quoteString('apple')
        * "apple"
        *
        * >>> jQuery.quoteString('"Where are we going?", she asked.')
        * "\"Where are we going?\", she asked."
        */
        $.quoteString = function (string) {
            if (string.match(escapeable)) {
                return '"' + string.replace(escapeable, function (a) {
                    var c = meta[a];
                    if (typeof c === 'string') {
                        return c;
                    }
                    c = a.charCodeAt();
                    return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
                }) + '"';
            }
            return '"' + string + '"';
        };

    })(jQuery);

