﻿
/* global font */

function createCookie(name,value,hours) {
    var expires = "";
    if (hours) {
        var date = new Date();
        date.setTime(date.getTime() + (hours * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + escape(value) + expires + "; path=/;";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(nameEQ) === 0) {
            return unescape(c.substring(nameEQ.length, c.length));
        }
    }
    return null;
}

var bugRiddenCrashPronePieceOfJunk = (navigator.userAgent.indexOf('MSIE 5') != -1 && navigator.userAgent.indexOf('Mac') != -1);

var W3CDOM = (!bugRiddenCrashPronePieceOfJunk && document.getElementsByTagName && document.createElement);

function setActiveStyleSheet(title, reset) {
  
  if (!W3CDOM){return false;}
    var i, a, main;

    if (reset == 1) {
        createCookie("wstyle", title, 8760);
        jQuery('.activefont').removeClass('activefont');
    } 
      
    for(i = 0; a = document.getElementsByTagName("link")[i]; i++) {
        if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
            a.disabled = true;

            if (a.getAttribute("title") == title) {
                a.disabled = false;
                jQuery('.activefont').removeClass('activefont');
                if (title == "Large font")
                    jQuery('.largefontlink').addClass('activefont');
                else
                    jQuery('.mediumfontlink').addClass('activefont');
            }
        }
    }
}

function setStyle() {

    var style = readCookie("wstyle");
    if (style !== null) {
        setActiveStyleSheet(style, 0);
    }
}

function registerEventListener(elem, event, func) {
    if (elem.addEventListener) {
        elem.addEventListener(event, func, false);
        return true;
    } else if (elem.attachEvent) {
        var result = elem.attachEvent("on"+event, func);
        return result;
    }

    return false;
}

function registerPloneFunction(func) {
     registerEventListener(window, "load", func);
}

registerPloneFunction(setStyle);

/* Hide/style elements with javascript before loaded */
function createStyleRule(selector, declaration) {
    jQuery("<style type='text/css' media='screen'>"+selector+"{"+declaration+"}</style>").appendTo('head');
}

/* Slideshow/movie player */

/*
function resize(newHeight, animTime) {
    jQuery(".c_mainimage").height(newHeight);
    //jQuery(".c_mainimage").animate({height: newHeight}, animTime);
}

function isReady() {
    return true;
}

function sendToActionScript() {
    return "returnedFromJavaScript";
}
*/

var animVars;

function initResizer() {
    animVars = {
        t: null,
        swf: document.getElementById("visitviewer"),
        container: document.getElementById("visitviewer").parentNode,
        h: document.getElementById("visitviewer").parentNode.offsetHeight,
        to_h: 0,
        d: 10
    };
}

function resize(newHeight, animTime) {
    if (newHeight < 50 || animVars.to_h == newHeight) return;
    animVars.to_h = newHeight;
    //animVars.t = setInterval( function() { animSizeEasy(animVars.t); }, 35);
    animVars.t = setInterval("animSizeEasy()", 35);
}

function isReady() {
    if (!animVars) initResizer();
    return true;
}

function sendToActionScript() {
    return "returnedFromJavaScript";
}

function animSizeEasy() {

    animVars.h += (animVars.to_h - animVars.h) * .3;

    if (Math.abs(animVars.h - animVars.to_h) < 1) {
        animVars.h = animVars.to_h;
        clearInterval(animVars.t);
    }

    animVars.container.style.height = animVars.swf.style.height = animVars.h + "px";
}

function animSizeLinear() {
    var done = false;
    
    if (animVars.h > animVars.to_h) {
        if (animVars.h - animVars.d < animVars.to_h) {
            animVars.h = animVars.to_h;
            done = true;
        }
        else {
            animVars.h -= animVars.d;
        }
    }
    else if (animVars.h < animVars.to_h) {
        if (animVars.h + animVars.d > animVars.to_h) {
            animVars.h = animVars.to_h;
            done = true;
        }
        else {
            animVars.h += animVars.d;
        }
    }
    else {
        done = true;
    }

    animVars.container.style.height = animVars.swf.style.height = animVars.h + "px";
    
    if (done) clearInterval(animVars.t);
}

function toggleCampaign(visibility) {
	if (visibility) {
		jQuery('.sponsortag').show();
	}
	else {
		jQuery('.sponsortag').hide();
	}
}

/* Remove title properties in Safari SiteSelector */

function fixSiteSelector() {
    if (jQuery.browser.safari) {
        jQuery(".c_siteselector a").attr("title", "");
    }
}

/* PNGfix */

function pngfix(imgselector) {
    var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
    var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
    if (jQuery.browser.msie && (ie55 || ie6)) {
        jQuery(imgselector).load(function() {
            pngfiximage(this);
        });
    }
}

function pngfiximage(img) {
    jQuery(img).attr('width', jQuery(img).width());
    jQuery(img).attr('height', jQuery(img).height());

    var prevStyle = '';
    var strNewHTML = '';
    var imgId = (jQuery(img).attr('id')) ? 'id="' + jQuery(img).attr('id') + '" ' : '';
    var imgClass = (jQuery(img).attr('class')) ? 'class="' + jQuery(img).attr('class') + '" ' : '';
    var imgTitle = (jQuery(img).attr('title')) ? 'title="' + jQuery(img).attr('title') + '" ' : '';
    var imgAlt = (jQuery(img).attr('alt')) ? 'alt="' + jQuery(img).attr('alt') + '" ' : '';
    var imgAlign = (jQuery(img).attr('align')) ? 'float:' + jQuery(img).attr('align') + ';' : '';
    var imgHand = (jQuery(img).parent().attr('href')) ? 'cursor:hand;' : '';
    if (img.style.border) {
        prevStyle += 'border:' + img.style.border + ';';
        img.style.border = '';
    }
    if (img.style.padding) {
        prevStyle += 'padding:' + img.style.padding + ';';
        img.style.padding = '';
    }
    if (img.style.margin) {
        prevStyle += 'margin:' + img.style.margin + ';';
        img.style.margin = '';
    }
    var imgStyle = (img.style.cssText);

    strNewHTML += '<span ' + imgId + imgClass + imgTitle + imgAlt;
    strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;' + imgAlign + imgHand;
    strNewHTML += 'width:' + jQuery(img).width() + 'px;' + 'height:' + jQuery(img).height() + 'px;';
    strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(img).attr('src') + '\', sizingMethod=\'scale\');';
    strNewHTML += imgStyle + '"></span>';
    if (prevStyle != '') {
        strNewHTML = '<span style="position:relative;display:inline-block;' + prevStyle + imgHand + 'width:' + jQuery(img).width() + 'px;' + 'height:' + jQuery(img).height() + 'px;' + '">' + strNewHTML + '</span>';
    }

    jQuery(img).hide();
    jQuery(img).after(strNewHTML);
}

/* Filter Select Plugin */

(function ($) {
	$.fn.vnSelect = function (options) {
		this.each(function () {
			var $target = $(this), vnSelect;
			if ($target.data('vnSelect')) { return $target; }
			vnSelect = new VNSelect($target, options);
			$target.data('vnSelect', vnSelect);
		});
	};

	function VNSelect($target, options) {
		var defaults = { },
            $ul, $li, $liParent, $box, liRel,
            selectedText = '',
            $parent = $target.parent();
            targetClass = $target.attr('class');
		options = $.extend({}, defaults, options);

        $target.hide();
        $parent.addClass(targetClass + "Replaced");

        $ul = $('<ul></ul>')
            .addClass('filterSelect')
            .hover(
		        function() { $(this).addClass('selHover'); },
		        function() { $(this).removeClass('selHover'); }
	        );

        $target.children().each(function(i, el) {
            $li = $('<li><a href="#">' + $(el).text() + '</a></li>')
		        .attr('rel', $(el).attr('value'))
		        .hover(
			        function() { $(this).addClass('hover'); },
			        function() { $(this).removeClass('hover'); }
		        )
		        .click(function() {
		            $(this).addClass('selected').siblings().removeClass('selected');
		            $ul.removeClass('selectOpen')
                        .find('.box a').text($(this).text()).focus();
                    liRel = $(this).attr('rel');
		            if (liRel == "0") {
		                $target.val("");
		            } else {
		                $target.val(liRel);
		            }
		            return false;
		        });

            if ($(el).is(':selected')) {
                $li.addClass('selected');
                selectedText = $(el).text();
            }

            $ul.append($li);
        });
        $ul.append($("<li><a href='#'></a></li>"))
            .find("a:last").blur(function() {
                $ul.removeClass('selectOpen');
            });

        $box = $('<li class="box" title="' + $target.attr('title') + '"><div class="selectbox_top"><div class="selectbox_lefttop"><div class="selectbox_righttop"></div></div></div><div class="selectbox_body"><div class="selectbox_left"><div class="selectbox_right"><div class="selectbox_content"><a href="#">' + selectedText + '</a></div></div></div></div><div class="selectbox_bottom"><div class="selectbox_leftbottom"><div class="selectbox_rightbottom"></div></div></li>')
	        .hover(
		        function() { $(this).addClass('hover'); },
		        function() { $(this).removeClass('hover'); }
	        )
	        .click(function(event) {
	            $(this).parent().toggleClass('selectOpen');
	            // Close others
	            $(".filterSelect").each(function() {
	                if ($(this).get(0) != $ul.get(0)) {
	                    $(this).removeClass('selectOpen');
	                }
	            });
	            return false;
	        });

        $ul.prepend($box);
        $target.after($('<div class="c_filterSelect"></div>').append($ul));
    }
})(jQuery);

function geoCallback(st)
{
    alert(st);
}

function setMapPointer(x, y) {
    alert(x);
}

/* Language Bar */

function checkLanguage(pageId, currentLanguageCode, queryString, serviceUrl) {
    // Read from cookie
    var languageChosen = readCookie("languagechosen");

    if (!languageChosen) {

        var webMethod = serviceUrl + '/WebServices2/LanguageService.aspx';
        var parameters = "pageId=" + pageId + "&currentLanguageCode=" + currentLanguageCode + "&queryString=" + queryString + "&callback=?";

        jQuery.ajax({
            type: "GET",
            url: webMethod,
            data: parameters,
            dataType: "jsonp",
            success: function(data) {
                jQuery('.c_pageheader').before(data.d);
                jQuery('.c_languagebar .langclose a').click(function() {
                    // Save to cookie
                    createCookie("languagechosen", 1, 8760);
                    jQuery('.c_languagebar').remove();
                    return false;
                })
            },
            error: function(xhr, ajaxOptions, thrownError) {
                //alert(xhr.status);
                //alert(thrownError);
            }

        });
    }
}

function toggleIconPopup(popupId, iconObj, img_mo) {
    var thePopup = jQuery(popupId);
    /*var thePopup;
    if (popupId) {
        thePopup = jQuery(popupId);
    }
    else {
        console.log($(iconObj).next('a'));
        thePopup = $(iconObj).next('a');
    }*/
    
    if (thePopup.parent()[0].tagName.toLowerCase() != 'body') {
        thePopup = thePopup.detach();
        thePopup
            .appendTo('body')
            .hover(
                function() {
                    jQuery(this).css('display', 'block');
                },
                function() {
                    jQuery(this).css('display', 'none');
                }
            );
        // Adjust marker position
        mapMarker = thePopup.find('.mappreview_marker');
        if (mapMarker.length > 0) {
            var mX = parseFloat(mapMarker.css('left'));
            mapMarker.css('left', mX + 5 + "px");
            var mY = parseFloat(mapMarker.css('top'));
            mapMarker.css('top', mY + 5 + "px");
        }
    }
    var icon = jQuery(iconObj).find("img");
    var offset = icon.offset();
    
    // Adjust popup position
    var popoup_xpos = offset.left - (thePopup.width() / 2) + 14;
    var content_offset = jQuery('#c_maincontent').offset();
    if (popoup_xpos < content_offset.left) {
        var arrow = thePopup.children('img.arrow');
        var oldLeft = (thePopup.width() / 2) - (arrow.width() / 2);
        var newLeft = -13 + oldLeft - (content_offset.left - popoup_xpos);
        newLeft = Math.max(newLeft, 2);
        arrow.css('left', newLeft + "px");
        popoup_xpos = content_offset.left;
    }
    popoup_xpos = Math.max(popoup_xpos, content_offset.left);
    // Draw popup
    thePopup
        .css('left', popoup_xpos + "px")
        .css('top', offset.top - thePopup.height() + 9 + "px")
        .css('display', 'block');
    icon.attr("rel", icon.attr("src"));
    icon.attr("src", img_mo);
    jQuery(iconObj).mouseout(function() {
        jQuery(thePopup).css('display', 'none');
        icon.attr("src", icon.attr("rel"));
    });
}

// PRODUCT PAGE SLIDESHOW

function initProductSlideshow() {
    var PS_IMGPERPAGE = 5,
	    PS_THUMBHEIGHT = 57,
	    PS_SLIDEMODE = 1,
	    PS_MAPMODE = 2,
	    $sb = jQuery("#productslideshow .ps_thumbnails"),
	    $th = jQuery("#productslideshow .ps_thumbnailscontent"),
	    imgCount = jQuery("#productslideshow .ps_sidebar a").length,
	    ps_tabdirection = 1,
	    ps_mode = PS_SLIDEMODE;

	// Slide click
	jQuery("#productslideshow .ps_sidebar a").click(function() {
		ps_mode = PS_SLIDEMODE;
		var idx = jQuery(this).index();
		jQuery(this).addClass("selected").siblings().removeClass("selected");
		jQuery("#productslideshow .ps_maps a").removeClass("selected");
		jQuery("#productslideshow .ps_slide:eq(" + idx + ")").show().siblings('.ps_contentitem').hide();
		return false;
	});
	jQuery("#productslideshow .ps_sidebar a").mousedown(function() {
		return false;
	});
	
	// Create page navigation
	if ($th.height() > $sb.height()) {
		jQuery("<div class='ps_down enabled' id='ps_down'>Next page</div>")
			.hide()
			.appendTo("#productslideshow .ps_sidebar");
		jQuery('#ps_down.enabled').live('click', scrollpage);
		jQuery("<div class='ps_up enabled' id='ps_up'>Previous page</div>")
			.hide()
			.appendTo("#productslideshow .ps_sidebar");
		jQuery('#ps_up.enabled').live('click', scrollpage);
		
		updatepaging(true);
		
		// Show/hide page navigation
		jQuery(".ps_sidebar").hover(
			function() {
				jQuery("#ps_up.enabled, #ps_down.enabled").stop(true, true).fadeIn();
			},
			function() {
				jQuery("#ps_up, #ps_down").stop(true, true).fadeOut();
			}
		);
	}

	// Create image navigation
	if (jQuery("#productslideshow .ps_slide").length > 1) {
		jQuery("<div class='ps_right'>Next image</div>")
			.hide()
			.click(imgNavigate)
			.appendTo("#productslideshow .ps_content");
		jQuery("<div class='ps_left'>Previous image</div>")
			.hide()
			.click(imgNavigate)
			.appendTo("#productslideshow .ps_content");

		// Show/hide image navigation
		jQuery(".ps_content").hover(
			function() {
				if (ps_mode == PS_SLIDEMODE) jQuery(".ps_right, .ps_left").stop(true, true).fadeIn();
			},
			function() {
				jQuery(".ps_right, .ps_left").stop(true, true).fadeOut();
			}
		);
	}
	// Position small images
	var totHeight = jQuery('#productslideshow .ps_content').height();
	
	jQuery('#productslideshow .ps_content img').each(function(idx, el) {
	    el = jQuery(el);
	    el.load(function() { positionImage(el); });
	    var s = el.attr('src');
	    el.attr('src', '');
	    el.attr('src', s);
	});
	
	function positionImage($img) {
		var thisHeight = $img.height();
	    if (thisHeight < totHeight) {
		    var newTop = Math.round((totHeight / 2) - (thisHeight / 2));
		    var totWidth = jQuery('#productslideshow .ps_content').width();
		    var newLeft = Math.round((totWidth / 2) - ($img.width() / 2));
		    $img.css({ "position": "absolute", "left": newLeft+"px", "top": newTop + "px" });
	    }
	}
	
	// Select first thumbnail
	jQuery("#productslideshow .ps_sidebar a:eq(0)").addClass('selected');

	// Image prev/next navigation
	function imgNavigate() {
		var direction = (jQuery(this).attr('class') == "ps_right") ? 1 : -1;
		var idx = jQuery("#productslideshow .ps_sidebar a.selected").index();
		var nextIdx = idx + direction;
		
		// Looping
		if (nextIdx >= imgCount) nextIdx = 0;
		else if (nextIdx < 0) nextIdx = imgCount-1;
		
		scrollToSelected(nextIdx);
		jQuery("#productslideshow .ps_sidebar a:eq(" + nextIdx + ")").click();
	}
	
	// Image select scroll
	function scrollToSelected(idx) {
		if (idx === undefined) idx = jQuery("#productslideshow .ps_sidebar a.selected").index();
		var currentPage = Math.floor(idx/PS_IMGPERPAGE);
		
		var top = parseInt($th.css('top'));
		if (top + 0 != top) top = 0;
		
		var toTop = -currentPage * PS_THUMBHEIGHT *PS_IMGPERPAGE;
		
		if (top != toTop) {
			$th.stop(true, false).animate({ top: -currentPage * PS_THUMBHEIGHT *PS_IMGPERPAGE }, 500, function() {
				updatepaging(true);
			});
		}
	}
	
	// Image page scroll
	function scrollpage() {
		var direction = (jQuery(this).hasClass('ps_down')) ? 1 : -1;
		var sbHeight = imgCount * PS_THUMBHEIGHT;
		
		var top = parseInt($th.css('top'));
		if (top + 0 != top) top = 0;
		
		var toTop = top - (direction * PS_THUMBHEIGHT * PS_IMGPERPAGE);
		jQuery("#ps_up, #ps_down").removeClass('enabled');
		$th.stop(true, false).animate({ top: toTop }, 500, updatepaging);
	}
	
	// Update paging buttons
	function updatepaging(hide) {
		var thHeight = imgCount * PS_THUMBHEIGHT;
		var sbHeight = $sb.height();
		
		var top = parseInt($th.css('top'));
		if (top + 0 != top) top = 0;
		
		if (top >= 0)
			jQuery("#ps_up").removeClass('enabled').fadeOut(300);
		else {
			jQuery("#ps_up").addClass('enabled');
			if (!hide) jQuery("#ps_up").fadeIn(300);
		}
		
		if (top-sbHeight <= -thHeight)
			jQuery("#ps_down").removeClass('enabled').fadeOut(300);
		else {
			jQuery("#ps_down").addClass('enabled');
			if (!hide) jQuery("#ps_down").fadeIn(300);
		}
	}

}

/* PRODUCT PAGE: SHORTEN DESCRIPTION */

function shortenDescription() {
    var MAX_HEIGHT = 16.1; // unit: em
    var TOLERANCE = 6; // unit: em
    var $nt = jQuery(".normaltext");
    var origHeight = $nt.height() / 11; // font-size: 1.1em
    if (origHeight > MAX_HEIGHT + TOLERANCE) {
        var $fader = jQuery("<div class='pp_fader' />");
        jQuery("#pp_showdesc").show().click(function() {
            $nt.animate({height: origHeight+"em"}, 300);
            $fader.remove();
            jQuery(this).hide(300);
            return false;
        });
        $nt.css({"height": MAX_HEIGHT+"em", "position": "relative", "overflow": "hidden"})
            .append($fader);
        //IE6 pngfix:
        if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7) {
            $fader.css({
                'background':'none',
                'filter':'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="/images/product/overlay_fade.png", sizingMethod="scale")'
            });
        }
    }
}


/* HoverPopup plugin */

(function (jQuery) {

    jQuery.fn.vnHoverPopup = function(options) {
        this.each(function () {
            var target = jQuery(this);
            if (target.data('vnHoverPopup')) return target;
            var vnHoverPopup = new VNHoverPopup(target, options);
            target.data('vnHoverPopup', vnHoverPopup);
        });
    };

    function VNHoverPopup($target, options) {
        var defaults = {
            triggerselector: '.pop_trigger',
            popupselector: '.pop_popup',
            insertposselector: null,
            popupposition: 'left',
            offsetx: 0,
            offsety: 0,
            hoverdelay: 200,
            click: false
        };
        options = jQuery.extend({}, defaults, options);

        var timeoutID,
            popupsPositioned,
            $triggers = $target.find(options.triggerselector),
            $popups = $target.find(options.popupselector);

        init();

        function init() {
            if (options.insertposselector) {
                $popups.remove().appendTo(options.insertposselector);
            }
            $popups.hide();
            $popups.each(function(idx, el) {
				var $link = jQuery($triggers[idx]),
					$popup = jQuery(el);
			    
                $popup
                    .data('index', idx)
                    .css({
				        position: 'absolute',
				        'z-index': 1001
			        }).hover(
					    function() { 
                            window.clearTimeout(timeoutID);
                            jQuery(this).show();
                        },
					    function() {
                            jQuery(this).hide();
					    }
				    );
                    
                $link.hover(
					function() { mouseOverHandler($popup) },
					function() { mouseOutHandler($popup) }
				);

                if (options.click) {
                    $link.click(function() {
                        if ($popup.is(':visible')) {
                            mouseOutHandler($popup);
                        }
                        else {
                            mouseOverHandler($popup);
                        }
                        return false;
				    });
                }
            
            });
        }

        function mouseOverHandler($popup) {
            timeoutID = window.setTimeout(function() { showPopup($popup) }, options.hoverdelay);
        }

        function mouseOutHandler($popup) {
            window.clearTimeout(timeoutID);
            timeoutID = window.setTimeout(function() { hidePopup($popup) }, options.hoverdelay);
        }

        function showPopup($popup) {
            positionPopup($popup);
            $popup.show();
        }

        function hidePopup($popup) {
            $popup.hide();
        }

        function positionPopup($popup) {
  			var idx = $popup.data('index'),
                $link = jQuery($triggers[idx]),
				pos = $link.position(),
                xpos = pos.left,
                ypos = pos.top;

            switch (options.popupposition) {
                case 'top':
                    ypos -= $popup.height();
                    break;
                case 'bottom':
                    ypos += $link.height();
                    break;
                case 'right':
                    $popup.addClass('pop_popup_left');
                    xpos += $link.width();
                    break;
                case 'left':
                    xpos -= $popup.width();
                    break;
            }

            $popup.css({
				left: Math.floor(xpos + options.offsetx) + 'px',
				top: Math.floor(ypos + options.offsety) + 'px'
			});
	    }
    }
})(jQuery);


/* Dropdown plugin */

(function (jQuery) {

    jQuery.fn.vnDropdown = function(options) {
        this.each(function () {
            var target = jQuery(this);
            if (target.data('vnDropdown')) return target;
            var vnDropdown = new VNDropdown(target, options);
            target.data('vnDropdown', vnDropdown);
        });
    };

    function VNDropdown($target, options) {
        var defaults = {
            selectedselector: '.ddl_selected',
            choicesselector: '.ddl_choices',
            insertposselector: null,
            hoverdelay: 200
        };
        options = jQuery.extend({}, defaults, options);

        var $selected = $target.find(options.selectedselector),
            $choices = $target.find(options.choicesselector),
            $selected_a = $selected.find('a'),
            $choices_a = $choices.find('a'),
            timeoutID;

        init();

        function init() {
            var selWidth = (jQuery.trim($selected_a.text()).length * .7) + 1.6;
            $target.css('width', selWidth + 'em');
            if (options.insertposselector) {
                $selected_a.keydown(function(event) {
                    if (event.keyCode == 9 && $choices.is(':visible')) {
			            event.preventDefault();
                        $choices_a.first().focus();
			        }
                });
                $choices.remove().appendTo(options.insertposselector);
            }

		    jQuery.each([$choices, $selected], function() {
		        this.hover(
				    mouseOverHandler,
				    mouseOutHandler
			    );
			});

            $selected_a.bind('click', function() {
                mouseOverHandler();
                return false;
            });

            jQuery('<a href="#" class="ddl_last" \>')
                .bind('click blur focus', function() {
                    mouseOutHandler();
                    return false;
                })
                .appendTo($choices);

            // Safari tooltip hover bug: Remove title attributes
            if (jQuery.browser.safari) {
                $choices_a.removeAttr('title');
            }
        }
        
        
        function mouseOverHandler() {
            window.clearTimeout(timeoutID);
            if (options.insertposselector) {
                var pos = $target.position();
                $choices.css({
                    position: 'absolute',
                    top: (pos.top + $target.height()) + 'px',
                    left: pos.left + 'px',
                    width: ($target.width() - 3) + 'px',
                    'z-index': 999
                });
            }
            $choices.show();
        }

        function mouseOutHandler() {
            window.clearTimeout(timeoutID);
            timeoutID = window.setTimeout(hideChoices, options.hoverdelay);
        }

        function hideChoices() {
            $choices.hide();
        }

    }
})(jQuery);

/* Datepicker wrapper */

vnDatepickerRange = function (options) {
    var defaults = {
        fromID: 'ctl00_mainContentRegion_leftContentRegion_txtFromDate',
        toID: 'ctl00_mainContentRegion_leftContentRegion_txtToDate',
        langCode: 'en',
        helpText: 'Ctrl+arrow keys can be used to navigate.'
    };
    options = jQuery.extend({}, defaults, options);

    jQuery(document).ready(function () {
        var selectedMin = null,
			selectedMax = null,
			$textInputs = jQuery('#' + options.fromID + ' , #' + options.toID),
			lastOpened,
			daySelected = false,
            showWeekNum = false,
            mouseUsed = false,
            minDate = null,
            isOpen = false,
            periodLength = 0,
            $patch,
            $datepickerStyle;

        // Modify langCode if necessary
        switch (options.langCode) {
            case 'en': case 'us':
                options.langCode = 'en-US';
                break;
            case 'uk':
                options.langCode = 'en-GB';
                break;
            case 'cn':
                options.langCode = 'zh-CN';
                break;
            case 'dk':
                options.langCode = 'da';
                break;
            case 'se':
                options.langCode = 'sv';
                break;
        }
        jQuery.datepicker.setDefaults(jQuery.datepicker.regional[options.langCode]);

        var dates = $textInputs.datepicker({
            numberOfMonths: 2,
            showWeek: showWeekNum,
            minDate: new Date(),
            showAnim: '',
            beforeShow: function (input, inst) {
                lastOpened = this.id;
                isOpen = true;
                daySelected = false;
                minDate = jQuery(this).datepicker('option', 'minDate');
                updateHelpText();
                updatePosition();
                jQuery(input).parent().addClass('datepickerOpen').siblings().removeClass('datepickerOpen');
                updatePatch(input);
                if (!mouseUsed) {
                    _gaq.push(['_trackEvent', 'Datepicker', 'Open Keyboard', lastOpened]);
                }
            },
            onSelect: function (selectedDate) {
                _gaq.push(['_trackEvent', 'Datepicker', 'Select Day ' + selectedDate, lastOpened]);

                var option = this.id == options.fromID ? 'minDate' : 'maxDate',
					instance = jQuery(this).data('datepicker'),
					date = jQuery.datepicker.parseDate(instance.settings.dateFormat || jQuery.datepicker._defaults.dateFormat, selectedDate, instance.settings);
                if (option == 'minDate') {
                    selectedMin = date;
                    dates.not(this).datepicker('option', option, date); // Disable days before
                    if (selectedMin > selectedMax) {
                        selectedMax = selectedMin;
                        $textInputs.last().datepicker('setDate', selectedMax);
                    }
                }
                else {
                    selectedMax = date;
                    periodLength = selectedMax - selectedMin;
                }
                daySelected = true;
            },
            beforeShowDay: function (date) {
                var instance = jQuery(this).data('datepicker'),
					formattedDate = jQuery.datepicker.formatDate(instance.settings.dateFormat || jQuery.datepicker._defaults.dateFormat, date, instance.settings),
					title = jQuery(this).attr('title') + ': ' + formattedDate;

                if (selectedMin != null && selectedMax != null &&
				date.getTime() >= selectedMin.getTime() &&
				date.getTime() <= selectedMax.getTime()) {
                    // Mark from date
                    if ((this.id == options.toID && date.getTime() == selectedMin.getTime()) || date.getTime() == selectedMin.getTime()) {
                        return [true, 'ui-state-range-from', title];
                    }
                    // Mark to date
                    else if ((this.id == options.fromID && date.getTime() == selectedMax.getTime()) || date.getTime() == selectedMax.getTime()) {
                        return [true, 'ui-state-range-to', title];
                    }
                    return [true, 'ui-state-range', title];
                }
                else if (selectedMin != null && date.getTime() == selectedMin.getTime()) {
                    return [true, 'ui-state-range-from', title];
                }
                else if (selectedMax != null && date.getTime() == selectedMax.getTime()) {
                    return [true, 'ui-state-range-to', title];
                }

                // Remove title on disabled dates
                if (date < minDate) title = '';

                return [true, '', title];
            },
            onClose: function () {
                if (!daySelected) {
                    _gaq.push(['_trackEvent', 'Datepicker', 'Close', lastOpened]);
                }

                isOpen = false;

                jQuery(this).parent().removeClass('datepickerOpen');
                $patch.hide();
            },
            onChangeMonthYear: function (year, month, inst) {
                updateHelpText();
            }
        });

        // Select default range
        var dpLast = $textInputs.last().data('datepicker'),
            dpFirst = $textInputs.first().data('datepicker');
        selectedMax = jQuery.datepicker.parseDate(dpLast.settings.dateFormat || jQuery.datepicker._defaults.dateFormat, $textInputs.last().val(), dpLast.settings);
        selectedMin = jQuery.datepicker.parseDate(dpFirst.settings.dateFormat || jQuery.datepicker._defaults.dateFormat, $textInputs.first().val(), dpFirst.settings);
        periodLength = selectedMax - selectedMin;

        $textInputs.each(function () {
            var $textInput = jQuery(this);

            $textInput
            .click(function () {
                _gaq.push(['_trackEvent', 'Datepicker', 'Open Textfield', $textInput.attr('id')]);
            })
            .keyup(function (e) {
                if ((e.keyCode < 48 || e.keyCode > 57) && jQuery.inArray(e.keyCode, [46, 8, 13]) === -1) return;

                var instance = jQuery(this).data('datepicker'),
					newDate = jQuery.datepicker.parseDate(instance.settings.dateFormat || jQuery.datepicker._defaults.dateFormat, $textInput.val(), instance.settings);
                if (this.id == options.fromID) selectedMin = newDate;
                else selectedMax = newDate;
                $textInput.datepicker('refresh');
                updateHelpText();
            });

            $textInput.next('input').click(function (e) {
                _gaq.push(['_trackEvent', 'Datepicker', 'Open Icon', $textInput.attr('id')]);
                $textInput.datepicker('show');
                return false;
            });
        });

        $textInputs.mousedown(function () {
            mouseUsed = true;
        });
        $textInputs.next('input').mousedown(function () {
            mouseUsed = true;
        });

        function updateHelpText() {
            if (mouseUsed) {
                //mouseUsed = false;
                return;
            }
            setTimeout(function () {
                if (mouseUsed) return;
                jQuery('#ui-datepicker-div').find('.ui-datepicker-row-break').html('<p>' + options.helpText + '</p>');
            }, 10);
        }

        function updatePosition() {
            if (!$datepickerStyle || $datepickerStyle.length == 0) {
                $datepickerStyle = jQuery('<style type="text/css" media="screen"></style>').appendTo('head');
            }
            var fromPos = $textInputs.first().offset();
            if (fromPos) {
                $datepickerStyle.replaceWith('<style type="text/css" media="screen">#ui-datepicker-div {left:' + fromPos.left + 'px !important; top:' + (fromPos.top + $textInputs.first().height() + 2) + 'px !important;}}</style>');
            }
        }
        jQuery(window).resize(function () {
            updatePosition();
            updatePatch(jQuery('#' + lastOpened));
        });

        function updatePatch(input) {
            if (!$patch) {
                $patch = jQuery('<div id="ui-datepicker-patch">&nbsp;</div>').appendTo('body');
            }
            var $inputContainer = jQuery(input).parent(),
			    containerOffset = $inputContainer.offset();
            if (containerOffset) {
                $patch.css({
                    top: Math.round(containerOffset.top + $inputContainer.height() + 10) + 'px',
                    left: Math.round(containerOffset.left + 1) + 'px',
                    width: Math.round($inputContainer.width() + 32) + 'px'
                }).show();
            }
        }

        // Tracking
        jQuery('#ui-datepicker-div .ui-datepicker-prev').live('mouseup', function () {
            var state = jQuery(this).hasClass('ui-state-disabled') ? ' Disabled' : '';
            _gaq.push(['_trackEvent', 'Datepicker', 'Click Previous Month' + state, lastOpened]);
        });
        jQuery('#ui-datepicker-div .ui-datepicker-next').live('mouseup', function () {
            _gaq.push(['_trackEvent', 'Datepicker', 'Click Next Month', lastOpened]);
        });
        jQuery('#ui-datepicker-div .ui-datepicker-title').live('mouseup', function () {
            _gaq.push(['_trackEvent', 'Datepicker', 'Click Month Title', lastOpened]);
        });
        jQuery('#ui-datepicker-div td.ui-state-disabled:not(".ui-datepicker-other-month")').live('mouseup', function () {
            var beforeWhat = (jQuery(this).text() < new Date().getDate()) ? "Today" : "From Date";
            _gaq.push(['_trackEvent', 'Datepicker', 'Click Day Disabled Before ' + beforeWhat, lastOpened]);
        });
        jQuery('#ui-datepicker-div th').live('mouseup', function () {
            _gaq.push(['_trackEvent', 'Datepicker', 'Click Weekday Title', lastOpened]);
        });
    });
};

/* Breadcrumbs */

(function ($) {
	$.fn.vnBreadcrumbs = function (options) {
		this.each(function () {
			var $target = $(this),
				vnBreadcrumbs;
			if ($target.data('vnBreadcrumbs')) { return $target; }
			vnBreadcrumbs = new VNBreadcrumbs($target, options);
			$target.data('vnBreadcrumbs', vnBreadcrumbs);
		});
	}

	function VNBreadcrumbs($target, options) {
		var defaults = {
			hoverdelay: 200,
			maxheight: 285,
			canvaswidth: 740,
			maxcols: 4
		},
			timeoutID,
			curHeight,
			sumHeight,
			sumWidth,
			$bcDiv,
			$bcUl,
            $curUls,
			colWidth,
			curDivPos,
			panelRight,
            numCols = 1,
            $dropShadow1 = $('<div class="breadcrumb_dropshadow" />').insertBefore($target),
            $dropShadow2 = $('<div class="breadcrumb_dropshadow" />').insertBefore($target),
			shadowdeltax = -10,
            menuWidth = 0,
            menuMaxWidth = $target.parent().width(),
            $moreCrumb = $target.find('.breadcrumb_more'),
            moreCrumbWidth;
		options = $.extend({}, defaults, options);

        function init() {
            if($.browser.msie && $.browser.version < 8) {
                createStyleRule('.breadcrumb_dropshadow', 'border-color: pink; filter: chroma(color=pink);');
            }

            /* Trim if too wide */
            menuWidth = $moreCrumb.show().outerWidth() + $target.find('.breadcrumb_home').outerWidth();
            $moreCrumb.hide();
            trimmed = false;
            $($target.children('li:not(".breadcrumb_more, .breadcrumb_home")').get().reverse()).each(function () {
			    var $li = $(this),
                    liWidth = $li.outerWidth();

                if (trimmed) {
                    $li.remove();
                    return true;
                }
                //console.log(liWidth, ' ', menuWidth, ' ', menuMaxWidth);

                if (menuWidth + liWidth < menuMaxWidth) {
                    menuWidth += liWidth;
                }
                else {
                    if (!trimmed) {
                        $moreCrumb.show();
                        trimmed = true;
                    }
                    $li.remove();
                }
		    });
            
            /* Open on hover */
		    $target.children('li:not(".breadcrumb_empty, .breadcrumb_home, .breadcrumb_more")').hover(
			    function () {
				    var $li = $(this);
				    timeoutID = window.setTimeout(function () { openCrumb($li); }, options.hoverdelay);
			    },
			    function () {
				    var $li = $(this);
				    window.clearTimeout(timeoutID);
				    timeoutID = window.setTimeout(function () { closeCrumb($li); }, options.hoverdelay);
			    }
		    );
            
            /* Distribute sub items */
		    $target.find('div').each(function () {
			    sumHeight = curHeight = sumWidth = 0;
                numCols = 1;
			    $bcDiv = $(this);
			    $bcUl = $bcDiv.find('ul');
                $bcLis = $bcUl.find('li');
			    $curUl = $('<ul/>');
			    $curUls = $curUl;
                $bcDiv.show();
                colWidth = $bcUl.width();
                
                // Get all heights
                var liHeight = [];
                var itemsHeight = 0;
			    $bcLis.each(function(idx) {
				    liHeight[idx] = $(this).outerHeight();
				    itemsHeight += liHeight[idx];
			    });
                $bcDiv.hide();

                // Get numcols
                var itemNumCols = Math.ceil(itemsHeight/options.maxheight);
                itemNumCols = Math.min(itemNumCols, options.maxcols);
                //console.log(itemsHeight, itemNumCols, items);

                
                // Get stopheight
                var itemStopHeight = (itemsHeight/itemNumCols) + 20;
                itemStopHeight = Math.min(itemStopHeight, options.maxheight);
                //console.log(itemStopHeight);

			    $bcLis.each(function(idx) {
				    if (sumHeight + liHeight[idx] > itemStopHeight) {
                        jQuery.merge($curUls, $curUl);
					    if (!sumWidth) sumWidth = colWidth;
					    sumWidth += colWidth;
					    $bcDiv.width(numCols * colWidth);
                        
                        if (numCols >= options.maxcols) {
                            return false;
                        }

                        numCols++;
					    $curUl = $('<ul/>')
					    sumHeight = 0;
				    }
				    $(this).appendTo($curUl);
				    sumHeight += liHeight[idx];
			    });
                $bcUl.remove();

                // dupe
                jQuery.merge($curUls, $curUl);
			    if (!sumWidth) sumWidth = colWidth;
			    sumWidth += colWidth;
			    $bcDiv.width(numCols * colWidth);

                $bcDiv.append($curUls).hide();

			    curDivPos = $bcDiv.parent().position();
			    panelRight = curDivPos.left + $bcDiv.width();

			    if (panelRight > options.canvaswidth + shadowdeltax) {
				    $bcDiv.css('margin-left', (options.canvaswidth - panelRight - shadowdeltax) + 'px');
			    }
		    });
        }
        init();

		function openCrumb($li) {
            var liPos, paddingTop, divPos, $div, ds1Width, ds2Width;

			$li.addClass('crumb_open').find('div').show();

            liPos = $li.position();
            paddingTop = parseInt($li.css('margin-top'));
            
            ds1Width = Math.round($li.innerWidth()+1),
            $dropShadow1.width(ds1Width);
            $dropShadow1.height($li.outerHeight());
            $dropShadow1.css({
                top: Math.round(liPos.top + paddingTop) + 'px',
                left: Math.floor(liPos.left + shadowdeltax) + 'px'
            });
            $dropShadow1.show();

            $div = $li.find('div');
            divPos = $div.position();
            ds2Width =  Math.max($div.outerWidth(), ds1Width);
            $dropShadow2.width(ds2Width);
            $div.width(ds2Width-2);
            $dropShadow2.height($div.outerHeight());
            $dropShadow2.css({
                top: Math.round(liPos.top + divPos.top + paddingTop + 1) + 'px',
                left: Math.round(Math.floor(liPos.left) + shadowdeltax + 1 + parseInt($div.css('margin-left'))) + 'px'
            });
            $dropShadow2.show();
		}

		function closeCrumb($li) {
			$li.removeClass('crumb_open').find('div').hide();
            $dropShadow1.hide();
            $dropShadow2.hide();
		}

	}
})(jQuery);


(function ($) {
	$.fn.vnButtonify = function (options) {
		this.each(function () {
			var $target = $(this),
				vnButtonify;
			if ($target.data('vnButtonify')) { return $target; }
			vnButtonify = new VNButtonify($target, options);
			$target.data('vnButtonify', vnButtonify);
		});
	};

	function VNButtonify($target, options) {
		var defaults = {
		},
		options = $.extend({}, defaults, options);

		$target.find('a.vnbutton').each( function () {
			var html = $('<div>').append($(this).removeClass('vnbutton').clone()).remove().html(),
                newEl = $('<div class="c_vnbutton vnbutton_replaced"><div class="white_button"><div class="vnbutton_top"><div class="vnbutton_lefttop"><div class="vnbutton_righttop">&nbsp;</div></div></div><div class="vnbutton_body"><div class="vnbutton_left"><div class="vnbutton_right">' + html + '</div></div></div><div class="vnbutton_bottom"><div class="vnbutton_leftbottom"><div class="vnbutton_rightbottom">&nbsp;</div></div></div></div></div>')
                    .hover(function () {
                        //console.log($(this));
                        $(this).toggleClass("c_vnbuttonhover");
                    });

			$(this).replaceWith(newEl);
		});
	}
})(jQuery);

(function ($) {
    var methods = {
        init: function(options) {
            return this.each(function () {
			    var $target = $(this),
				    vnShoppingCart;
			    if ($target.data('vnShoppingCart')) { return; }
			    vnShoppingCart = new VNShoppingCart($target, options);
			    $target.data('vnShoppingCart', vnShoppingCart);
		    });
        },
        update: function()  {
            return this.each(function () {
			    var vnShoppingCart = $(this).data('vnShoppingCart');
			    if (vnShoppingCart) {
                    vnShoppingCart.update();
                }
		    });
        }
    };

    $.fn.vnShoppingCart = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        }
        else {
            $.error('Method ' +  method + ' does not exist on jQuery.vnShoppingCart');
        }
    };
    /*
	$.fn.vnShoppingCart = function (options) {
		this.each(function () {
			var $target = $(this),
				vnShoppingCart;
			if ($target.data('vnShoppingCart')) { return $target; }
			vnShoppingCart = new VNShoppingCart($target, options);
			$target.data('vnShoppingCart', vnShoppingCart);
		});
	};
    */
	var VNShoppingCart = function($target, options) {
		var defaults = {
                maxCountries: 3,
                maxFilters: 5
		    },
		    options = $.extend({}, defaults, options),
            $cartContents = $target.find('div.order_cart_contents'),
            $linkMinimize = $target.find('a.order_section_cart a.order_cart_minimize'),
            $linkOpen = $target.find('a.order_section_cart a.order_cart_open'),
            $boxCountries = $target.find('div.order_section_country'),
            $boxCountriesLis = $boxCountries.find('li'),
            $boxCountriesMore = $boxCountries.find('li.order_change_country_dots, li.order_change_country_link'),
            $boxFiltersMore = $target.find('div.order_section_language a.order_filter_show')
            cartIsOpened = false,
            filtersIsOpened = false;

        // Public update function
        this.update = function() {
            if (cartIsOpened) {
                $target.find('.order_cart_contents, .order_section_cart .order_cart_minimize').show();
                $target.find('.order_section_cart .order_cart_open').hide();
            }
            $boxFiltersMore = $target.find('div.order_section_language a.order_filter_show');
            filtersTruncate();
        };

        $('.c_maincontainer_content').css('padding-bottom', '40em');
        
        // Initialize countries dropdown
        $boxCountries.vnHoverPopup({
            popupposition: 'bottom',
            click: true,
            offsety: 3
        });
        //$target.find('a.pop_trigger').click(function () { return false });
        /*
        // Truncate countries dropdown
        if ($boxCountriesLis.length > options.maxCountries + 4) {
            $boxCountriesLis.slice(options.maxCountries).hide();
            $boxCountriesMore.show();
            $boxCountriesMore.click(function () {
                $boxCountriesLis.slideDown();
                $boxCountriesMore.slideUp();
                return false;
            });
        }
        */
        // Truncate filters
        function filtersTruncate() {
            if (filtersIsOpened) return false;
            $('.order_section_filter').each(function () {
                var $filter = $(this),
                    $labels = $filter.find('label');
                if ($labels.length > options.maxFilters) {
                    $labels.slice(options.maxFilters).hide();
                    $boxFiltersMore.show();
                    $boxFiltersMore.click(function () {
                        filtersIsOpened = true;
                        $labels.slideDown();
                        $boxFiltersMore.hide();
                        return false;
                    });
                }
            });
        }
        filtersTruncate();

        // Initialize shopping cart minimizing
        $target.find('.order_section_cart h2').live('click', function () {
            var $contents = $target.find('.order_cart_contents').slideToggle('normal', function () {
                if ($contents.is(':visible')) {
                    cartIsOpened = true;
                    $target.find('.order_section_cart .order_cart_minimize').show();
                    $target.find('.order_section_cart .order_cart_open').hide();
                    $target.find('.order_section_cart h3').css('margin-bottom', '.4em');
                }
                else {
                    cartIsOpened = false;
                    $target.find('.order_section_cart .order_cart_minimize').hide();
                    $target.find('.order_section_cart .order_cart_open').show();
                }
            });
            return false;
        });

        // Initialize fly-to-basket
        $target.find('a.order_product_add').live('click', function () {
            var $this = $(this).parents('.order_product'),
                $img = $this.find('.order_product_image img'),
                $basket = $target.find('.order_section_cart .order_cart_itemcount'),
                productX = $img.offset().left,
		        productY = $img.offset().top,
		        basketX = $basket.offset().left,
		        basketY = $basket.offset().top
		        newImageWidth = $img.width() / 3,
		        newImageHeight = $img.height() / 3;
		
            $img
		        .clone()
		        .css({
                    'position': 'absolute',
                    'left': productX,
                    'top': productY,
                    'z-index': '10002'
                })
		        .appendTo('body')
		        .animate({opacity: 0, left: basketX, top: basketY, width: newImageWidth}, 1000, function() {
				    $(this).remove();
                });
        });
	}
})(jQuery);

/* Slideshow plugin */
(function ($) {

    $.fn.vnSlideshow = function (options) {
        this.each(function () {
            var target = $(this);
            if (target.data('vnSlideshow')) return target;
            var vnSlideshow = new VNSlideshow(target, options);
            target.data('vnSlideshow', vnSlideshow);
        });
    };

    function VNSlideshow($target, options) {
        var slideAnimID,
			$slideNavi = $target.find('.slide_navigation'),
			$slideProgress,
			$slideProgressIcons,
			$imgs,
			$photoTexts = $target.find('#phototextdiv .imgtext');
        options = $.extend({}, {
            slideSelector: 'img.main_image',
            fadeDuration: 300,
            playDuration: 4000,
            progressPosition: 'center'
        }, options);
        $imgs = $target.find(options.slideSelector);

        $imgs.css({
            'display': 'block',
            'position': 'absolute',
            'top': 0,
            'left': 0
        }).first().addClass('current_image');
        $imgs.not('.current_image').hide();

        $slideProgress = $('<div class="slide_progress" />').show();
        for (i = 0; i < $imgs.length; i++) {
            $slideProgress.append('<div />')
        }

        if (!Modernizr.touch) {
            $slideNavi.find('a.next, a.prev').hide();
        }

        if (options.progressPosition == 'center') {
            $slideProgress.css('left', 1 + ($target.width() / 2) - ($imgs.length * 4));
        }
        $slideProgressIcons = $slideProgress.find('div');
        $slideProgressIcons.first().addClass('current');
        $slideNavi.append($slideProgress);

        $slideNavi.find('a.next').click(function () {
            slideTo($imgs.index($imgs.filter('.current_image')) + 1);
            clearInterval(slideAnimID);
            return false;
        });

        $slideNavi.find('a.prev').click(function () {
            slideTo(($imgs.index($imgs.filter('.current_image')) - 1) + $imgs.length);
            clearInterval(slideAnimID);
            return false;
        });

        function slideTo(idx) {
            idx %= $imgs.length;
            var $nextImage = $imgs.eq(idx);

            $nextImage
				.stop(true, false)
				.addClass('current_image')
				.fadeIn(options.fadeDuration, function () {
				    $imgs.not('.current_image').hide();
				}
			).siblings().removeClass('current_image');

            $slideProgressIcons.eq(idx).addClass('current').siblings().removeClass('current');
            $photoTexts.eq(idx).addClass('imgtext_current').siblings('.imgtext').removeClass('imgtext_current');
        }

        slideAnimID = setInterval(function () {
            slideTo($imgs.index($imgs.filter('.current_image')) + 1);
        }, options.playDuration);

        $target.hover(function () {
            $slideNavi.find('a').fadeIn();
        }, function () {
            $slideNavi.find('a').fadeOut();
        });

    }
})(jQuery);

/* Book Norway Search Widget */

(function ($) {
    $.fn.vnSearchWidget = function (options) {
        this.each(function () {
            var target = $(this), vnSearchWidget;
            if (target.data('vnSearchWidget')) return target;
            $(document).ready(function(){
                vnSearchWidget = new VNSearchWidget(target, options);
                target.data('vnSearchWidget', vnSearchWidget);
            });
        });
    };

    function VNSearchWidget($target, options) {
        options = $.extend({}, {
            selectedTab: 0,
            minimized: false,
            productParameter: '',
            areaParameter: '',
            lang: 'en',
            cssParameter: '&css=/styles/visitnorway_searchwidgets.css',
            scriptUrl: 'http://bookingtest.visitnorway.com/en',
            delayTime: 0,
            failTime: 24000,
            defaultCategoryId: ';defaultCategoryId=',
            widgets: [
                {c: 'accommodationwidget', a: 'searchform', p: this.defaultCategoryId},
                {c: 'carrentalwidget', a: 'searchform', p: ''},
                {c: 'flightwidget', a: 'searchform', p: ''},
                {c: 'ferrywidget', a: 'searchform', p: ''}
            ],
            title_ac: 'Accommodation',
            title_fl: 'Flights',
            title_cr: 'Car Rental',
            title_fe: 'Ferry',
            title_as: 'Activities',
            baseUrl: '/combinewidget/combine?'
        }, options);

        var checkInterval, startTime, $searchelms, widgets_script, s, w, tabClass, params, timePassed, $minimized
            $tabbox = $('#bn_tabbox'),
            $bestprice = $('#bn_bestprice');

        if (!options.delayTime) {
            options.delayTime = 0;
        }

        $target.find('.bn_fallback').hide();

        $('#bn_tab_ac').attr({ href: '#bn_ac', title: options.title_ac });
        $('#bn_tab_fl').attr({ href: '#bn_fl', title: options.title_fl });
        $('#bn_tab_cr').attr({ href: '#bn_cr', title: options.title_cr });
        $('#bn_tab_fe').attr({ href: '#bn_fe', title: options.title_fe });
        $('#bn_tab_as').attr({ href: '#bn_as', title: options.title_as });

        if (options.minimized) {
            $minimized = $target.find('.bn_minimized').show();
            $target.find('.bn_widget:eq(' + options.selectedTab + ')').hide();
            $target.find('.widget_open').click(function () {
                $minimized.slideUp("normal", function () {
                    $(this).remove();
                    $target.find(".bn_widget").slideDown("normal");
                });
                return false;
            });
        }

        $('#bn_tabbox').tabs({
            selected: options.selectedTab,
            select: function (event, ui) {
                $('.tipsy').remove();
                $target.find('.bn_widget').show();
                $target.find('.bn_minimized').remove();
                showBestPrice(ui);
            }
        });

        function showBestPrice(ui) {
            if (!$tabbox.length) return;
            tabClass = (ui) ? $(ui.tab).attr('class') : $('#bn_tabbox').find(".ui-state-active a").attr("class");
            $bestprice.find('.' + tabClass).show().siblings().hide();
        }
        showBestPrice();

        function generateScriptUrl() {
            params = [];
            baseUrl = options.baseUrl;
            if (options.widgets.length > 1) {
                for (w = 0, len = options.widgets.length; w < len; w++) {
                    params.push(
                    'c=' + options.widgets[w].c,
                    'a=' + options.widgets[w].a,
                    'p=alignDirection=1' + options.productParameter + options.widgets[w].p + options.areaParameter
                );
                }
            }
            else {
                baseUrl = '/' + options.widgets[0].c + '/' + options.widgets[0].a + '?';
                params.push('alignDirection=1', options.cssParameter.replace(';', ''));
                if (options.productParameter) {
                    params.push(options.productParameter.replace(';', ''));
                }
                if (options.areaParameter) {
                    params.push(options.areaParameter.replace(';', ''));
                }
            }
            return options.scriptUrl + baseUrl + params.join('&') + options.cssParameter;
        }

        widgets_script = document.createElement('script');
        widgets_script.type = 'text/javascript';
        widgets_script.async = true;
        widgets_script.src = generateScriptUrl();
        s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(widgets_script, s);

        function startLoading() {
            $searchelms = $("#c_rightmaincontent .bn_header,.bn_title,#bn_tabbox").hide();
            $("#bn_searchbox_loading, #bn_searchbox_error").insertAfter('#bn_tabbox');
            $("#bn_searchbox_loading").show();

            startTime = new Date().getTime();
            checkInterval = setInterval(checkIt, 250);
        }
        function checkIt() {
            timePassed = new Date().getTime() - startTime;
            if (timePassed < options.delayTime) return;
            if ($("#citybreak_accommodation_searchform_widget").html().length > 0) {
                clearInterval(checkInterval);
                $searchelms.show();
                $("#bn_searchbox_loading, #bn_searchbox_error").hide();
            }
            else if (timePassed > options.failTime) {
                $("#bn_searchbox_loading").hide();
                $("#bn_searchbox_error").show();
            }
        }
        startLoading();
    }
})(jQuery);

jQuery(document).ready(function () {
	jQuery('ul.breadcrumbs').vnBreadcrumbs();
    jQuery('#c_leftmaincontent .normaltext').vnButtonify();

    // Video icon hover fade
    if (!(jQuery.browser.msie && parseInt(jQuery.browser.version) < 8)) {
        jQuery('img.filmplayicon, img.smallfilmpreviewicon').parent().hover(
            function () {
                jQuery(this).find('img.filmplayicon, img.smallfilmpreviewicon').stop().fadeTo(500, 1);
            },
            function () {
                jQuery(this).find('img.filmplayicon, img.smallfilmpreviewicon').stop().fadeTo(500, 0.6);
            }
        );
    }
});

/* EOF */
