﻿// Netonnet.js
// In this file we collect general scripts that are used through out the site.
//-------------------------------------------------------------------------------------

(function($) {
    $.fn.equalHeights = function(minHeight, maxHeight) {
        tallest = (minHeight) ? minHeight : 0;
        this.each(function() {
            if ($(this).height() > tallest) {
                tallest = $(this).height();
            }
        });
        if ((maxHeight) && tallest > maxHeight) tallest = maxHeight;
        return this.each(function() {
            $(this).height(tallest + 3).css("overflow", "visible");
        });
    }
})(jQuery);

//
// Description: Toggles a div (infoElementId) when the link (linkElementId) is clicked. 
// For an example look at paymenttypes or freight types in cart.
//---------------------------------------------------------------------------------
toggleInfoText = function(infoElementId, linkElementId, hideText, showText) {
    if ($('#'+infoElementId).hasClass("ui-helper-hidden")) {
        $('#' + linkElementId).text(hideText);
    } else {
    $('#' + linkElementId).text(showText);
    }

    $('#' + infoElementId).toggleClass("ui-helper-hidden");
}

toggleGiftCardForm = function(infoElementId) {
    $('#' + infoElementId).toggleClass("ui-helper-hidden");
}

ShowModalAlertBox = function(headline, text, buttonText) {
    var text = '<div class="popup"><div class="layer"><div class="innerlayer"><div class="formRowHeadline"><div class="exclimationMark">!</div><h3>' + headline + '</h3></div><div>' + text + '</div><br/><div class="buttonContainer"><input id="postalCodeWarningDialogCancel" class="btn simplemodal-close" type="button" value="' + buttonText + '"/></div></div></div>';
    $(text).modal({ position: ["35%", "40%"] });
}


//
// Description: Performs an ajax request.
// onsuccess: method called if the request is successful
// onerror: method called if the request is not successful
//---------------------------------------------------------------------------------
function PerformAjax(url, onsuccess, onerror, data) {

    if (data == null) {
        data = '{}'
    }

    $.ajax({
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        data: data,
        cache: false,
        url: url,
        dataType: "json",
        beforeSend: function(xhr) { xhr.setRequestHeader('connection', 'close'); },
        success: onsuccess,
        error: onerror
    });
}

//
// Description: Performs an ajax request.
// onsuccess: method called if the request is successful
// onerror: method called if the request is not successful
//---------------------------------------------------------------------------------
function PerformAjaxHtmlReturn(url, onsuccess, onerror, data) {
    if (data == null) {
        data = '{}'
    }
    
    // Debug code to be removed in live site.
    if (onerror == null) {
        onerror = function(error) { } //alert(error); }
    }

    $.ajax({
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        data: data,
        cache: false,
        url: url,
        dataType: "html",
        success: onsuccess,
        error: onerror
    });
}

//
// Description: Does a redirect from a json result.
//---------------------------------------------------------------------------------
function RedirectFromJsonResult(data) {
    var url = "";
    if (data.Url != "" && data.Url != null) {
        url = data.Url
    }
    else {

        url = url + "/" + data.Controller;
        if (data.Action != "") {
            url = url + "/" + data.Action;
        }
        if (data.Parameters.length > 0) {
            for (i = 0; i < data.Parameters.length; i++) {
                url = url + "/" + data.Parameters[i].Value;
            }
        }
    }
    return url;
}

function UpdateCartInformation(data) {
    if (data.ItemCount == 0)
        SetCartTopContracted();

    if (data.Url != null && data.Url != "" || data.Controller != null && data.Controller != "") {
        window.location.href = RedirectFromJsonResult(data);
    }
    else {
        $("#cartBodyContainer").load("/Cart/GetShoppingCart/false");
    }
}

function SubscribeToNewsletter(data, status) {
    if (data.success == true) {
        var inputEmail = $('#newsletterEmail');
        inputEmail.val('');
        $('#newsletterEmailLabel').hide();
        inputEmail.hide();
        $('#newsletterSubscribeBtn').hide();
        $('#newsletterUnsubscribeBtn').hide();
        $('#newsletterInformation').hide();
        $('#newsletterResponseContent').html( data.message + '</span> ');
    } else {
        $('#newsletterResponseContent').html('<span class="errorMessage">' + data.message + '</span>');
    }
}

function UnsubscribeToNewsletter(data, status) {
    if(data.success == true) {
        var inputEmail = $('#newsletterEmail');
        inputEmail.val('');
        $('#newsletterEmailLabel').hide();
        inputEmail.hide();
        $('#newsletterSubscribeBtn').hide();
        $('#newsletterUnsubscribeBtn').hide();
        $('#newsletterInformation').hide();
        $('#newsletterResponseContent').html( data.message + '</span> ');
    } else {
        $('#newsletterResponseContent').html('<span class="errorMessage">' + data.message + '</span>');
    }
}

function AddItem(itemid, quantity) {
    $.scrollTo({ top: 0, left: 0 }, 500);
    $("#button_" + itemid).effect("transfer", { to: "#cartContainer" }, 500, function() {
        PerformAjax("/Cart/Add/" + itemid + "/" + String(quantity).substring(0,6), function(data) {
            if (data.Success) {
                $("#cartContainer").effect("shake", { times: 1, direction: "up", distance: 5 }, 100, function() {
                    UpdateCartInformation(data);
                    if (data.ShoppingCartExpanded) SetCartTopExpanded();
                });
            }
            else {
                ShowModalAlertBox(data.ClientMessageCaption, data.ClientMessage, "ok");
            }
        }, null);
    });
}

function AddSingleItem(itemid) {
    PerformAjax("/Cart/Add/" + itemid + "/1", UpdateCartInformation, null);
}

function AddInsurance(index, insuranceId) {
    if ($("#button_" + insuranceId).size() > 0) {
        $("#button_" + insuranceId).effect("transfer", { to: "#cartContainer" }, 500, function() {
            $("#cartContainer").effect("shake", { times: 1, direction: "up", distance: 5 }, 100);
            PerformAjax("/Cart/AddInsurance/" + index + "/" + insuranceId, UpdateCartInformation, null);
        });
    }
    else {
        $("#button_multipleInsurance").effect("transfer", { to: "#cartContainer" }, 500, function() {
            $("#cartContainer").effect("shake", { times: 1, direction: "up", distance: 5 }, 100);
            PerformAjax("/Cart/AddInsurance/" + index + "/" + insuranceId, UpdateCartInformation, null);
        });       
    }
}

function RemoveItemFromShoppingCart(itemId, index, callbackSuccess, callbackFailure) {
    $("#item" + itemId).hide("blind", options = {}, 500);
    RemoveItemFromCart(index, callbackSuccess, callbackFailure);
}
function RemoveItemFromCart(index, callbackSuccess, callbackFailure) {    
    PerformAjax("/Cart/RemoveByIndex/", callbackSuccess, callbackFailure, { index: index });
}

function RemoveHidden(id) {
    $(id).removeClass("ui-helper-hidden");
}

function SetCartTopExpanded() {
    $("#cartTop").css('background-position', 'bottom');
}
function SetCartTopContracted() {
    $("#cartTop").css('background-position', 'top');
}

function AddSubscription(id) {
    var chkBoxes = document.getElementsByName('addOns');
    var checkedIds = "";
    var portingId = "";
    var mobileNumber = "";
    var operator = "";
    for (i = 0; i < parseInt(chkBoxes.length); i++) {
        if (chkBoxes[i].checked) {
            if (checkedIds.length > 0) {
                checkedIds += "," + chkBoxes[i].value;
            }
            else {
                checkedIds += chkBoxes[i].value;
            }
        }
    }
    if (document.getElementById('mobileNumber')) {
        mobileNumber = document.getElementById('mobileNumber').value;
    }
    if (document.getElementById('operator')) {
        operator = document.getElementById('operator').value;
    }
    if (document.getElementById('portingId')) {
        portingId = document.getElementById('portingId').value;
    }

    var arr = "AddOns=" + checkedIds + "&PortingId=" + portingId + "&CurrentMobileNumber=" + mobileNumber + "&CurrentOperator=" + operator;

    PerformAjax('/Cart/AddSubscription/' + id, UpdateCartInformation, null, arr);

}




// This element suppose to be a link with className "plusMinus"
// and with a parent "display:none" and sibling ".expandBlock" to Work :)
// Example of use: Search for class="filterOptions"
function ExpandBlock(jQueryExpandLinkDefinition) {

    // Set state attribute
    if (!$(jQueryExpandLinkDefinition).attr("state") || $(jQueryExpandLinkDefinition).attr("state") == "closed") {
        $(jQueryExpandLinkDefinition).attr("state", "open").addClass("plusMinusOpen").siblings(".expandBlock").css("display", "block");
    }
    else {
        $(jQueryExpandLinkDefinition).attr("state", "closed").removeClass("plusMinusOpen").siblings(".expandBlock").css("display", "none");
    }

    return false;
}

// Clear form elements for a specific tag
// Example of use: Search for class="filterOptions"
function ClearInputFieldsByTag(jQueryElementTagDefinition) {

    $(jQueryElementTagDefinition + " input:text").attr("value", "");
    $(jQueryElementTagDefinition + " input:checkbox").removeAttr("checked");
    $(jQueryElementTagDefinition + " input:radio").removeAttr("checked");

    return false;
}


function PostAjaxForm(url, formName, callback) {
    $.post(url,
            $('#' + formName).serialize(),
            function(html) {
                callback(html);
            },
            'html');
}


//Description: Shows read more dialog for infobxes
function showDialogInfoBoxReadMore(id, title) {
    $('#ReadMoreDialog' + id).dialog({
        title: title, 
        autoOpen: false,
        bgiframe: true,
        padding: 10,
        width: 680,
        modal: true,
        draggable: false,
        closeOnEscape: true,
        resizable: false,
        close: function(ev, ui) { $(this).hide(); }
    });

    $('#ReadMoreDialog' + id).load("/Item/GetGetInfoboxReadMore", { InfoBoxId: id });
    $('#ReadMoreDialog' + id).show();
    $('#ReadMoreDialog' + id).dialog('open');
}

var Url = {

    // public method for url encoding
    encode: function(string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode: function(string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
}

// vars used by menuNodeToggle and menuNodeClick
if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7 && parseInt(jQuery.browser.version) > 4) {
    var doExtraIEStuff = true;
    var selectedEffect = null;
} else {
    var doExtraIEStuff = false;
    var selectedEffect = "blind";
}

var menuItemLoading = false;

//  Menu toggle function
function menuNodeToggle(id, level) {
    var show = false;
    
	if ($('#MenuLink' + id + ' + ul:hidden').size() > 0) {
		show = true;
	}

	var ll = parseInt(level);
	while (ll < 4) {
	    ll = ll + 1;
	    $('.menu_level' + ll + ' + li.bottom').remove();
	    $('.menu_level' + ll).removeClass("open");
	    $('.menu_level' + ll + ' a').removeClass("selected");
	    $('.menu_level' + ll + ' ul:visible').hide(selectedEffect);
	}

	$('.menu_level' + level + ' ul:visible').hide(selectedEffect);

	$('.menu_level' + level + ' + li.bottom').remove();
	$('.menu_level' + level).removeClass("open");
	$('.menu_level' + level + ' a').removeClass("selected");
	
	if (show) {
	    $('#MenuItem' + id + ' .ul' + level).show(selectedEffect);
		if (level == '1') {
			$('#MenuItem' + id).addClass("open");
			$('#MenuItem' + id).after('<li class="bottom">&nbsp;</li>');
		}
		else {
			$('#MenuItem' + id).addClass("open");
			$('#MenuLink' + id).addClass("selected");
		}
		// Severe strange behaviour in IE6. Without this code the layout will be totally broken
		if (doExtraIEStuff) {
		    setTimeout(function() {
		        $('#MenuItem' + id + ' .ul' + level).hide();
		        setTimeout(function() {
		            $('#MenuItem' + id + ' .ul' + level).show();
		        }, 10);
		    }, 10);
		}
	}
	return false;
}
//  Loads child nodes in Menu
function menuNodeClick(id, level) {
    if ($('#MenuItem' + id + ' a').hasClass('node') && !menuItemLoading) {
        menuItemLoading = true;

        $('.menu_level' + level + ' ul:visible').hide(selectedEffect);
        $('.menu_level' + level + ' ul').hide();
        $('.menu_level' + level + ' + li.bottom').remove();
        $('.menu_level' + level).removeClass("open");
        $('.menu_level' + level + ' a').removeClass("selected");

        var ll = parseInt(level);
        while (ll < 4) {
            ll = ll + 1;
            $('.menu_level' + ll + ' + li.bottom').remove();
            $('.menu_level' + ll).removeClass("open");
            $('.menu_level' + ll + ' a').removeClass("selected");
            $('.menu_level' + ll + ' ul').hide();
        }

        $('#MenuItem' + id).load($('#MenuItem' + id + ' a').attr("href"), null, function(responseText, textStatus) {
            if (textStatus != 'error') {
                $('#MenuItem' + id + ' .ul' + level).show(selectedEffect);
                if (level == '1') {
                    $('#MenuItem' + id).addClass("open");
                    $('#MenuItem' + id).after('<li class="bottom">&nbsp;</li>');
                }
                else {
                    $('#MenuItem' + id).addClass("open");
                    $('#MenuLink' + id).addClass("selected");
                }
            }

            menuItemLoading = false;
        });

        return false;
    } else if (menuItemLoading) {
        menuItemLoading = false;
        return false;
    }
    menuItemLoading = false;
	return true;
}

// Supersleight plugin: png-fix for ie < 7
jQuery.fn.supersleight = function(settings) {
	settings = jQuery.extend({
		imgs: true,
		backgrounds: true,
		shim: '/Content/images/x.gif',
		apply_positioning: true
	}, settings);

	return this.each(function(){
		if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7 && parseInt(jQuery.browser.version) > 4) {
			jQuery(this).each(function(i,obj) {
				var self = jQuery(obj);

				if (settings.imgs && self.is('img[src$=png]')){
					var styles = {
						'display' : 'inline',
						'width': self.width() + 'px',
						'height': self.height() + 'px',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + self.attr('src') + "', sizingMethod='scale')"
					};
					self.css(styles).attr('src', settings.shim);
				};
				if (settings.applyPositioning && self.is('a, input') && self.css('position') === ''){
					self.css('position', 'relative');
				};
			});
		};
	});
};

//  ## setEqualHeight()
//  Description: Sets height of element2 to height of element1 if it's smaller
//  Usage: Call function after all content has been loaded (and tabs on item page has been set)
function setEqualHeight(el1, el2) {
    var el1Height = $(el1).height();
    var el2Height = $(el2).height();
    var maxHeight = (el1Height > el2Height) ? el1Height : el2Height;
    //alert(el1 +": "+ el1Height + "\n"+ el2 + ": "+ el2Height +"\nmaxHeight: " + maxHeight);
    var attr = "padding-bottom";
    if (maxHeight > el2Height) {
        $(el2).css(attr, maxHeight - el2Height + 'px');
    } else {
        $(el2).css(attr, '4px');
    }
}

var netonnetLib =
{
    // Site.Master
    //-------------
    site_master:
    {

        texts:
        {
            searchArticles: '',
            sectionPath: '',
            cartTopBgPos: '',
            colapseCart: '',
            expandCart: ''
        },

        // init
        //
        //---------------------------------
        init: function(objThis) {

            //            $("#showCartButton").live("click", function() {
            //                $(".cartExpandedContent").length > 0 ?
            //	                objThis.animateCart(".cartExpandedContent", ".cartContent", "top") :
            //	                objThis.animateCart(".cartContent", ".cartExpandedContent", "bottom");
            //                return false;
            //            });

        $(window).load(function() {
                objThis.setupSearch(objThis);
                $('.quantity').numeric({ ichars: 'åäö,-.' });
                $("#cartTop").css('background-position', objThis.texts.cartTopBgPos);
                objThis.bindClickEvents(objThis);
                $('.png').supersleight();
                if ($("#cartBodyContainer").length != 0) {
                    $("#cartBodyContainer").load("/Cart/GetShoppingCart/false", function() { setEqualHeight(".siteRightColumnContainer", ".siteMainContainer"); });
                }                
            });

            // Show popup when hover
            $(function() {
                $('.bubbleInfo').each(function() {
                    // options
                    var distance = 4;
                    var time = 100;
                    var hideDelay = 200;

                    var hideDelayTimer = null;

                    // tracker
                    var beingShown = false;
                    var shown = false;

                    var trigger = $('.trigger', this);
                    var popup = $('.popupcart', this).css('opacity', 0);

                    $([trigger.get(0)]).click(function() {
                        $(".cartExpandedContent").length > 0 ?
	                    objThis.animateCart(".cartExpandedContent", ".cartContent", "top") :
	                    objThis.animateCart(".cartContent", ".cartExpandedContent", "bottom");
                        return false;
                    });


                    // set the mouseover and mouseout on both element
                    $([trigger.get(0), popup.get(0)]).mouseover(function() {
                        // stops the hide event if we move from the trigger to the popup element
                        if (hideDelayTimer) clearTimeout(hideDelayTimer);

                        // don't trigger the animation again if we're being shown, or already visible
                        if (beingShown || shown) {
                            return;
                        } else {
                            beingShown = true;
                            // Change text depending on cart state
                            $(".cartExpandedContent").length > 0 ?
	                        $('.popupCartInfo').html(objThis.texts.colapseCart) :
	                        $('.popupCartInfo').html(objThis.texts.expandCart);

                            // reset position of popup box
                            popup.css({
                                top: -55,
                                left: -70,
                                display: 'block' // brings the popup back in to view
                            })

                            // (we're using chaining on the popup) now animate it's opacity and position
                            .animate({
                                top: '-=' + distance + 'px',
                                opacity: 1
                            }, time, 'swing', function() {
                                // once the animation is complete, set the tracker variables
                                beingShown = false;
                                shown = true;
                            });
                        }
                    }).mouseout(function() {
                        // reset the timer if we get fired again - avoids double animations
                        if (hideDelayTimer) clearTimeout(hideDelayTimer);

                        // store the timer so that it can be cleared in the mouseover if required
                        hideDelayTimer = setTimeout(function() {
                            hideDelayTimer = null;
                            popup.animate({
                                top: '-=' + distance + 'px',
                                opacity: 0
                            }, time, 'swing', function() {
                                // once the animate is complete, set the tracker variables
                                shown = false;
                                // hide the popup entirely after the effect (opacity alone doesn't do the job)
                                popup.css('display', 'none');
                            });
                        }, hideDelay);
                    });
                });
            });

        },

        // animateCart
        //
        //---------------------------------
        animateCart: function(toHide, toShow, bgPos) {
            var timeDelay = 400;
            if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 8 && parseInt(jQuery.browser.version) > 4) timeDelay = 0;

            var selectedEff = "blind", options = {}, timeDelay;

            $(toHide).hide(selectedEff, options, timeDelay,
                function() {
                    $("#cartBodyContainer").load("/Cart/GetShoppingCart/true",
		                function(responseText, textStatus, XMLHttpRequest) {
		                    if (textStatus != 'error') {
		                        $(toShow).show(selectedEff, options, timeDelay, function() { setEqualHeight(".siteRightColumnContainer", ".siteMainContainer"); });
		                    }
		                });
                    $("#cartTop").css('background-position', bgPos);
                });
        },

        // bindClickEvents
        //
        //---------------------------------
        bindClickEvents: function(objThis) {
            $('#newsletterSubscribeBtn').click(function() {
                PerformAjax('/newsletter/subscribe/' + $('#newsletterEmail').val(), SubscribeToNewsletter, null);
            });

            $('#newsletterUnsubscribeBtn').click(function() {
                PerformAjax('/newsletter/unsubscribe/' + $('#newsletterEmail').val(), UnsubscribeToNewsletter, null);
            });

            $('#newsletterDialogLink').click(function() {
                $("#newsletterDialog .layer").css({ width: "340px" });
                $("#newsletterDialog").modal({ position: ["25%", "50%"] });
            });
        },

        // setupSearch
        //
        //---------------------------------
        setupSearch: function(objThis) {
            var $searchQuery = $('#query');
            if ($searchQuery.val() == '') {
                $searchQuery.val(objThis.texts.searchArticles);
            }

            $searchQuery.focus(function() {
                if ($(this).val() == objThis.texts.searchArticles) {
                    $(this).val('');
                }
            }).blur(function() {
                if ($(this).val() == '') {
                    $(this).val(objThis.texts.searchArticles);
                }
            });

            $("#searchSubmit").click(function() {
                if ($searchQuery.val() == searchArticles || $searchQuery.val() == '') {
                    return false;
                }

                return true;
            });

            var $options = {
                script: "/suggest?",
                varname: "query",
                json: true,
                cache: true,
                shownoresults: false,
                timeout: 5000,
                minchars: 3,
                maxresults: 5
            };

            var as = new bsn.AutoSuggest('query', $options);
        }

    }
}
