﻿window.$BTJ.Carts = new function() {
    var $this = this;

    $this.init = function() {
        $this.configureAmountTextbox();
		$this.configureCartUpdateButton();
        $this.configureAddToCartButtons();
    };

    $this.ajaxItemAddedCallback = function(data, textStatus) {
		
        $(".HeadShoppingCart").html($(data).find(".HeadShoppingCart").html());
        window.$BTJ.Header.init();

        if (textStatus == "success") {

			// Update the content of the "in cart status" link
			var currentCartStatus = $(".currentArticle").find(".InCartStatus");
			if(currentCartStatus.length > 0) {
				var newCartStatusLink = $(data).find(".InCartStatus").html();
				currentCartStatus.html(newCartStatusLink); // replace current incartstatus-html
			} else {
				var newCartStatus = $(data).find(".ActionBar").html();
				$(".currentArticle").find('.ActionBar').prepend(newCartStatus); // add incartstatus-html
			}

			
        }
        
        $(".currentArticle").removeClass("currentArticles");
    } // end ajaxItemAddedCallback

    $this.getKeyEvent = function(event) {
        if (window.event) return event.keyCode;
        else return event.which;
    }

	
    /** 
    * Initiates the validation of the input of the buy configuration fields
    * @param selection  (optional) the part of the page affected by this initiation
    */
    $this.configureAmountTextbox = function(selection) {
        var trigger;
        if (undefined == selection) {
            trigger = $(".ConfCount");
        } else {
            trigger = $(selection).find(".ConfCount");
        }
        
        $this.configureOnlyNumericValues(trigger);
		$this.configureAddToCartButton(trigger);    
    }
    
    
    $this.configureAddToCartButton = function(trigger) {
		/* Enables and disables the 'add to cart' button */
        trigger.unbind('keyup');
        trigger.keyup(
			function(event) {
			    /* Check if there are any books to add */
			    var ok = false;
			    var article = $(this).closest(".Article");
			    article.find(".ConfCount").each(
					function(i, e) {
					    if (parseInt(e.value) > 0) ok = true;
					}
				);
			    /* Sets the button according to the result from above */
			    var button = article.find(".AddToCartBtn");
			    if (ok) {
			        $this.enableCartBtn(button);
			    } else {
			        $this.disableCartBtn(button);
			    }
			}
		);
    }
    
     /* Makes sure only numeric characters are entered */
    $this.configureOnlyNumericValues = function(trigger) {
		trigger.unbind('keypress');
        trigger.keypress(
			function(event) {
			    var key = $this.getKeyEvent(event);
			    if (key >= 48 && key <= 57) {
			        /* numeric input */
			    } else if (key == 0 || key == 8) {
			        /* arrow key, del, backspace */
			    } else {
			        /* other key */
			        event.returnValue = false;
			        event.preventDefault();
			    }
			}
		);
    }
    



    $this.disableCartBtn = function(button) {
        var disabledImageSrc = button.attr('disabledsrc');
        button.attr("src", disabledImageSrc);
        button.attr("disabled", "disabled");
    }

    $this.enableCartBtn = function(button) {
        var enabledImageSrc = button.attr('enabledsrc');
        button.attr("src", enabledImageSrc);
        button.attr("disabled", "");
    }

    $this.ajaxErrorCallback = function() {
        alert('Åtgärden misslyckades, okänt fel uppstod');
    }

    $this.configureCartUpdateButton = function() {

        // Configuring enable/disable of update button
        $this.configureEnableDisableUpdateButtonFromTextbox($(".AmountCol").find(".ConfCount"));
        $this.configureEnableDisableUpdateButtonFromTextbox($(".NotisRow").find(".InputRounded"));
        $this.configureEnableDisableUpdateButtonFromCheckbox($(".ConfDaily"));
        $this.configureEnableDisableUpdateButtonFromCheckbox($(".BibliPost"));
        $this.configureEnableDisableUpdateButtonFromDropDown($(".BibliPostMode"));
    }


	

    $this.configureEnableDisableUpdateButtonFromTextbox = function(inputs) {
        if(inputs.length > 0) {
			inputs.keyup(function(event) {
				var article = $(this).closest(".Article");
				$this.enableDisableUpdateButton(article);
			});
        }
    }

    $this.configureEnableDisableUpdateButtonFromCheckbox = function(inputs) {
		if(inputs.length > 0) {
			inputs.click(function(event) {
				var article = $(this).closest(".Article");
				$this.enableDisableUpdateButton(article);
			});
        }
    }
    
      $this.configureEnableDisableUpdateButtonFromDropDown = function(inputs) {
		if(inputs.length > 0) {
			inputs.change(function(event) {
				var article = $(this).closest(".Article");
				$this.enableDisableUpdateButton(article);
			});
        }
    }
    
    $this.checkIfUpdateButtonShouldBeEnabled = function(article) {
		// check if count has changed
		var confCounts = article.find(".AmountCol");
        var count1 = 0;
        var count2 = 0;
        var count3 = 0;
        confCounts.each(function(i, e) {
            if (i == 0 && $(e).find(".ConfCount").length > 0 && $(e).find(".ConfCount").val() != '') count1 = parseInt($(e).find(".ConfCount").val());
            if (i == 1 && $(e).find(".ConfCount").length > 0 && $(e).find(".ConfCount").val() != '') count2 = parseInt($(e).find(".ConfCount").val());
            if (i == 2 && $(e).find(".ConfCount").length > 0 && $(e).find(".ConfCount").val() != '') count3 = parseInt($(e).find(".ConfCount").val());
        });
        var oldCount1 = parseInt(article.children(".ConfCount1").html());
        var oldCount2 = parseInt(article.children(".ConfCount2").html());
        var oldCount3 = parseInt(article.children(".ConfCount3").html());
        if (count1 != oldCount1 || count2 != oldCount2 || count3 != oldCount3) {
			return true; 
         }
        
        // check if notes has changed
        var note1 = "";
        var note2 = "";
        var note3 = "";
        var notes = article.find(".NotisRow");
        notes.each(function(i, e) {
            if (i == 0 && $(e).find(".InputRounded").length > 0) { if ($(e).find(".InputRounded").attr("title") != $(e).find(".InputRounded").val()) note1 = $(e).find(".InputRounded").val(); };
            if (i == 1 && $(e).find(".InputRounded").length > 0) { if ($(e).find(".InputRounded").attr("title") != $(e).find(".InputRounded").val()) note2 = $(e).find(".InputRounded").val(); };
            if (i == 2 && $(e).find(".InputRounded").length > 0) { if ($(e).find(".InputRounded").attr("title") != $(e).find(".InputRounded").val()) note3 = $(e).find(".InputRounded").val(); };
        });
        var oldNote1 = article.children(".ConfNote1").html();
        var oldNote2 = article.children(".ConfNote2").html();
        var oldNote3 = article.children(".ConfNote3").html();
        
        if (note1 != oldNote1 || note2 != oldNote2 || note3 != oldNote3) {
			return true;
        }
        
        // check if Daily Delivery checkbox has changed
        var daily1 = false;
        var daily2 = false;
        var daily3 = false;
        var dailys = article.find(".DeliveryCol");
        dailys.each(function(i, e) {
            if (($(e).find(".ConfDaily").children().attr("checked"))) {
                if (i == 0) daily1 = true;
                if (i == 1) daily2 = true;
                if (i == 2) daily3 = true;
            }
        });
        var oldDaily1 = article.children(".DailyDeliv1").html() == "true";
        var oldDaily2 = article.children(".DailyDeliv2").html() == "true";
        var oldDaily3 = article.children(".DailyDeliv3").html() == "true";
        var post = false;
        if (daily1 != oldDaily1 || daily2 != oldDaily2 || daily3 != oldDaily3) {
			return true;
        }
        
        // check if Bibliographic post checkbox has changed
        if (article.find(".BibliPost").children().attr("checked")) post = true;
        var oldPost = article.children(".BibPost").html() == "true";
        if (post != oldPost) {
            return true;
        } 
       
       // check if Bibliographic post mode dropdown has changed
        var oldPostMode = article.children(".BibPostMode").html();
        var newPostMode = article.find(".BibliPostMode");
        if(newPostMode.length > 0 && newPostMode.val() != oldPostMode) {
			return true;
        }
        
        // nothing has changed
        return false;
    }

    $this.enableDisableUpdateButton = function(article) {
		
		var formDataChanged = $this.checkIfUpdateButtonShouldBeEnabled(article);
        if (formDataChanged) {
            $this.enableCartBtn(article.find(".jsUpdateCartBtn"));
        } else {
            $this.disableCartBtn(article.find(".jsUpdateCartBtn"));
        }
    }

    $this.setBuyButtonAction = function(trigger) {
        trigger.unbind('click');
        trigger.click(
			function(event) {
			    // collect parameter data
			    var params = "";
			    var bookconfirmation = $(this).parent();
			    var article = bookconfirmation.parent().parent();
			    var bookOptions = article.children(".BookOptions");
			    if (0 == bookOptions.length) {
			        bookOptions = article.children(".Snabbfakta").children(".BookOptions");
			    }
			    var optionRows = bookOptions.children(".BookOptionRow");
			    optionRows.each(
					function(i, e) {
					    // get conf-id value
					    var id = $(e).children("input.ConfId").val();
					    // get count value
					    var count = $(e).children(".AmountCol").children("input.InputRounded").val();
					    /* Clear the value of the count input field */
					    var txt = $(e).children(".AmountCol").children("input.InputRounded").val("");
					    if (count != null && count > 0) {
					        // add count value to param string
					        params += "&conf" + (i + 1) + "id=" + id + "&conf" + (i + 1) + "count=" + count;
					        // get 'daglig leverans' value
					        if ($(e).children(".DeliveryCol").children(".ConfDaily").children().attr("checked")) {
					            params += "&conf" + (i + 1) + "daily=true";
					        }
					        // get 'notis' value (check that value in notis textbox is not the default hintvalue)
					        var noteInputJs = $(e).parent().parent().children(".NotisFields").children(".NotisRow").children("input.InputRounded").get(i); // gets javascript-object
					        var noteInput = $(noteInputJs); // convert javascript-object to jQuery-object so we can use the jQuery methods
					        var hintValue = noteInput.attr('hintvalue');
					        if (noteInput.val() != "" && noteInput.val() != hintValue) {
					            params += "&conf" + (i + 1) + "note=" + encodeURIComponent(noteInput.val());
					        }

					        // clear 'notis' textbox value  (set it to the hintvalue again)
					        noteInput.val(hintValue);
					        noteInput.removeClass('FormHintActive');
					    }
					}

				);

			    if ("" == params) {
			        // has no selection to buy
			        alert("Ogiltigt antal"); //TODO should be done differently
			    } else {
			        params = "?cartid=" + bookconfirmation.children(".CartSelector").val() + params;
			        if (bookconfirmation.children("input.BibliPostCheck").attr("checked")) {
			            params += "&bibliographicPost=true";
			            
			             var bibPostMode = bookconfirmation.find(".BibliPostMode");
						 if(bibPostMode.length > 0) {
							params += "&bibPostMode=" + bibPostMode.val();
						 } 
			        }
			        // Remember which article we add an item to, will be used in ajax callback
			        $(".currentArticle").removeClass("currentArticle");
			        article.addClass("currentArticle");
			        var articleId = bookOptions.children(".ArticleID").html();
			        params += "&articleId=" + articleId + "&t=" + new Date().getTime(); //add timestamp to ensure we dont cache the ajax call
			        var ajaxurl = "/ajax/ajaxaddtoshoppingcart.aspx" + params;
			        $.ajax({
			            type: "POST",
			            url: ajaxurl,
			            success: $this.ajaxItemAddedCallback,
			            error: $this.ajaxErrorCallback
			        });
			        params = "";
			    }
			    $this.disableCartBtn($(this));
			    event.preventDefault();
			}
		);
    }
    /**
    * Adds actions to all Article related Buttons
    * @param selection  (optional) the part of the page affected by this initiation
    */
    $this.configureAddToCartButtons = function(selection) {
        if (undefined == selection) {
            $this.setBuyButtonAction($(".AddToCartBtn"));
        } else {
            $this.setBuyButtonAction($(selection).find(".AddToCartBtn"));
        }
    } // end configureAddToCartButtons
};

