// OVERRIDE - SHOPCOMMON
function DetectBrowser()
{
	Uagent = navigator.userAgent.toLowerCase();
	// Actions for firefox
	if(Uagent.indexOf("firefox") != -1) {
		ProductMenuTableHeightFix();
	}
	if($.browser.webkit){
		$("#ShopLayOut_Content_TD .TopMenu_TR").next().height(0);
	}
	
	// Copy main content HTML to print div layer
	GeneratePrintOutput();
}

/**
 * Before DOMReady: init
 **/
var pageUrl = CurrencyReturnUrl; 
var addthis_config = {
	data_track_clickback:true,
	ui_cobrand: "<strong>Frandeli</strong>",
	ui_header_color: "#ffffff",
	ui_header_background: "#000000",
	services_expanded: 'email, favorites, facebook, twitter, gmail, more',
	services_exclude: 'print',
	ui_language: "da"
};

// Hour of the day
var dateToday = new Date();
var theHour = dateToday.getHours();

/**
 * Autocomplete: Popular search terms
 **/
var searchwords= [
	'Triumph', 'Sloggi', 'Sloggi men', 'Tesa', 'bh', 'bukser', 'Rose', 'Shirley', 'Deco', 'Bianka', 'Amourette', 
	'babydoll', 'Freya', 'Dreamgirl', 'Dianette', 'Escante', 'Levante', 'Falke', 'Elomi', 'Margit Brandt',
	'Magic', 'cphluxe', 'Slimshaper', 'Nyce legs', 'Naomi nicole', 'Korset', 'Strømper', 'Underkjole',
	'Trusser', 'Bikini', 'Strømpebånd', 'badedragt', 'Push up', 'Åben', 'Hofteholder', 'JBS', 'String', 'Fauve',
	'G-streng', 'Babe', 'GYZ', 'Fantasie'
];

/**
 * Topmenu: Build top menu
 * 
 * @select(id): select menu item matching the given id
 **/
var topMenu = {
	select:function(id){
		selectedClass = (id == 'topMenu0' ? 'first-selected' : 'selected');		
		menuItem = $("#TopMenuTable").find("#" + id + ".menu-item");
		if(menuItem.length > 0){
			menuItem.addClass(selectedClass);
		}
	},
	dropdown:function(){
		$(".menu-item.has-dropdown").hover(function(){
			$(this).addClass("show-dropdown");
		},function(){
			$(this).removeClass("show-dropdown");
		});	
	}
}

/**
 * CMS pages: cms page spicific actions
 * 
 * @init(page): select menu item matching the given id
 **/
var cmsPage = {
	init:function(page){
		$("body").addClass("cmsPage");

		//submenu
		var cmsSubmenu = $("#cmsSubmenu");
		if(cmsSubmenu.length){
			$("#ProduktMenuHeader").html(cmsSubmenu.find("thead th").html());
			$("#ProductMenu_Table").html('<tbody>'+cmsSubmenu.find("tbody").html()+"</tbody>");
		}
		//specific pages		
		switch (page){
			case "/shop/cms-maerker.html":
				topMenu.select('topMenu5');
				$('.brand').hover(
					function(){ 
						$(this).find(".brandLogo").animate({height:"60%"},200); 
					},
					function(){ 
						$(this).find(".brandLogo").animate({height:"100%"},200); 
					}
				).find("a").click(function(){ 
					location.href = $(this).attr("href") 
				});
	  		break;
			default:
		}
	}
};

/**
 * Google maps
 **/ 
var gMap = {
	init: function(){
		apiKey = "ABQIAAAA7kxfVAxHWeNuoKCaiuaOsxTFxC6Aa_T5VMT7mVIRVhuXOFnqKBQDtYRp1hIO4SxKpezHP5xby1-BBA"

		$.getScript('http://www.google.com/jsapi?key='+apiKey, function() {
			google.load("maps", "3", {"callback" : mapsLoaded, other_params: "sensor=false&language=da"});
			
			function mapsLoaded(){
				var latlng = new google.maps.LatLng(55.839747, 12.545478);
				var mapOptions = {
					zoom: 15,
					center: latlng,
					mapTypeId: google.maps.MapTypeId.ROADMAP,
					mapTypeControlOptions: {
						style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
					}			  
				};
				
				var map = new google.maps.Map(document.getElementById("map"), mapOptions);
				
				var marker = new google.maps.Marker({
					position: latlng, 
					map: map, 
					title:"Her bor vi"
				});
	
				var infowindow = new google.maps.InfoWindow({
			    	content: '<h3>Frandeli - Next to the skin</h3>'+
					'<p>Tr&oslash;r&oslash;d Torv, Tr&oslash;r&oslash;dvej 58<br/>2950 Vedb&aelig;k</p>'
				});

				infowindow.open(map,marker);
				google.maps.event.addListener(marker, 'click', function() {
					infowindow.open(map,marker);
				});
			}
		});		
	}
};

/**
 * Gobal helper functions
 **/ 
var helpers = {
	findreplace: function(el, find, rep){
		try{
			$(el).html($(el).html().replace(find, rep))
		}catch(e){};
	},
	validate:{
		email:function(email){
	        var pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	        return pattern.test(email);
		}	
	}
}

/**
 * Newsletter hookup (CM)
 **/
var newsletter = {
	request:function(cmd, opts){
		if(cmd){
			// First, disable the form from submitting
            $(opts.form).submit(function() { return false; });
            
			emailVal = $(opts.email).val();
			nameVal = $(opts.name).val();
			submitBtn = $(opts.form).find("input:submit");

			// Validate email address with regex
			if (!helpers.validate.email(emailVal)) {
				alert("Der opstod et problem.\nDen indtastede e-mail ser ikke ud til at være korrekt indtastet!\nPrøv venligst igen.");
				return;
			}

			submitBtn.attr("disabled", "disabled");
            
            // Submit the form via ajax
            $.ajax({
                url: "/newsletter/proxy.asp",
                type: "POST",
                data: "cmd="+cmd+"&via="+opts.ref+"&name="+encodeURIComponent(nameVal)+"&email="+emailVal,
                success: function(data){
					submitBtn.removeAttr("disabled");
					if(typeof opts.onSucces == 'function'){
						opts.onSucces.call(this, data);
					}
                }
            });
		}
	}
};

/**
 * Long pagination fix
 **/
var paginationFix = {
	init:function(){
		$pagination = $("#PageNumbersTop, #PageNumbersBottom");
		$paginationCount = $("#PageNumbersTop a").length;

		if($paginationCount){
			if($paginationCount > 9){
				$pagination.html(function(){
					$thisEl = $(this);
					$thisEl.addClass("compact-pagination").html('<div class="compact-pagination-container">\
							<span class="info">Side: '+ $thisEl.find(".ActivePageNumber_ProductList").text() +' af '+ $paginationCount +'</span>\
							<div class="compact-pagination-dropdown"><span class="arrow"></span>\
								<div class="compact-pagination-inner">\
									<div class="compact-pagination-content">'+ $thisEl.html().replace(/(&nbsp;)*/g,"") + '</div>\
								</div>\
							</div>\
						</div>'
					);
				}).hoverIntent({
					over:function(){ $(this).find(".compact-pagination-dropdown").fadeIn(); },
					sensitivity:500,
					timeout:100,
					out:function(){ $(this).find(".compact-pagination-dropdown").fadeOut(); }
				});
			}else {
				$pagination.html($pagination.html().replace(/(&nbsp;)*/g,""));
			};
		}else {
			$pagination.parent().hide();
		}
	}
};

/**
 * Add to cart animation
 **/
var cartAnimation = {
	init:function(callbackFn){
		var source = $('#BUYSECTION input[type=image]');
		var target = $('#BasketTable');
		
		if(source.length){
			$('body').prepend('<div id="BuyButton_shadow" style="display:none; background-color: #000; position:static; top:0px; z-index: 100000;">&nbsp;</div>');
			var shadow = $('#BuyButton_shadow');

			shadow.width(source.css('width')).height(source.css('height')).css('top', source.offset().top).css('left', source.offset().left).css('opacity', 0.2).show();
			shadow.css('position', 'absolute');
			  
			shadow.animate({ width: target.innerWidth(), height: target.innerHeight(), top: target.offset().top, left: target.offset().left }, { duration: 500 })
			.animate( { opacity: 0 }, { duration: 100, complete:function(){
				target.animate({ left:"735px"}, { duration: 100, complete:function(){
					$(this).animate({ left:"725px"}, { duration: 100, complete:function(){
						$(this).animate({ left:"732px"}, { duration: 100, complete:function(){
							$(this).animate({ left:"728px"}, { duration: 100, complete:function(){
								$(this).animate({ left:"730px"}, 50);
								if(typeof callbackFn == 'function')
									callbackFn.call();							
							}});
						}});
					}});
				}});
				
				$(this).remove();
			}});
		}
	}
};

/**
 * DOMReady
 **/ 
$(document).ready(function() {
	/* :: Variables :: */
	$rootCatagory = $('#ShopMainLayOutTable #RootCatagory').val();	

	/* :: Day/Night theme :: */
	//if (theHour >= 18)
		//$('body').addClass('night');

	if(typeof $.fn.orbit == 'function'){
		// fade, horizontal-slide, vertical-slide, horizontal-push
		$('#frontpage-slider').orbit({ animation: 'horizontal-push', animationSpeed: 1000, timer: true, advanceSpeed: 5000, pauseOnHover: true, startClockOnMouseOut: true, startClockOnMouseOutAfter: 1000, directionalNav: true, captions: false, bullets: true });
	}

	//Facabook like button width fix - (invalid attr)
	$("#facebookLike").attr("fb:like:width", "160");

	/* :: Page specific events :: */
	topMenu.dropdown();
	
	// Hende
	if($rootCatagory==1437){
		topMenu.select('topMenu1');
	}
	// Ham
	if($rootCatagory==1478){
		topMenu.select('topMenu2');
	}
	// Mor
	if($rootCatagory==1439){
		$("#ProductmenuContainer_DIV").hide().siblings("#ProdMenuBottom").hide().next().css("marginTop","32px");	  
		topMenu.select('topMenu3');
	}
	// Plus size
	if($rootCatagory==1520){
		topMenu.select('topMenu8');
	}	
	// Velvære
	if($rootCatagory==1315){
		topMenu.select('topMenu4');
	}	
	// Jul2010
/*	if($rootCatagory==1468){
		topMenu.select('topMenu5');
	}
*/

	// Pagination fix
	paginationFix.init()
	
	// Specialoffers page
	if(pageUrl.indexOf('specialoffer-ALL-') != -1){
		$("#ProdGroupDescHeader").html("<h1>Udsalg</h1>");
		$("#ProdGroupDescBreadCrumb").html('<a href="/">Forside</a> &raquo; <span>Udsalg</span>');
		$("#ProductmenuContainer_DIV").hide().siblings("#ProdMenuBottom").hide().next().css("marginTop","32px");	  
		topMenu.select('topMenu7');
	}
	// Lastest products
	if(pageUrl.indexOf('news-ALL-') != -1){
		$("#ProdGroupDescHeader").html("<h1>Nyheder</h1>");
		$("#ProdGroupDescBreadCrumb").html('<a href="/">Forside</a> &raquo; <span>Nyheder</span>');
		$("#ProductmenuContainer_DIV").hide().siblings("#ProdMenuBottom").hide().next().css("marginTop","32px");
		topMenu.select('topMenu6');
	}
	// Search results (Keyword  != '')
	if(pageUrl.indexOf('search-') != -1){
		$ProdGroupDescHeader = $("#ProdGroupDescHeader");
		$ProdGroupDescHeader.html('<h1>Søgning: <small>"<i>'+Keyword+'</i>"</small></h1>');
		$("#ProdGroupDescBreadCrumb").html('<a href="/">Forside</a> &raquo; <span>Søg</span>');
		$('#SearchField').val($ProdGroupDescHeader.find("i").text());
		$("#ProductmenuContainer_DIV").hide().siblings("#ProdMenuBottom").hide().next().css("marginTop","32px");
		
		if($("#ProdListNumberOfProduct").length == 0){
			$("#ProductList_TD").wrapInner('<h1 id="ProdGroupDescHeader" />');
		}
	}
	if(pageUrl == ShowBasketUrl || pageUrl.indexOf('/shop/order') != -1 ){
		$("#banner-internal-03").hide();
	}
	// Product card
	if(ProductNumber != ""){
		// x for y a piece price.
		$("#ProdCardPrice .ProdCardPriceNow").each(function(i){
			if(!(i === 0)){
				$price  = $(this).find(".ProdCardPriceNowPrice").text();
				$amount = $(this).find(".ProdCardPriceNowAmount").text();
				$(this).text("v/"+ $amount +" stk. " + $price + " pr. stk.").addClass("ProdCardPriceMore");
			}
		});
		if(typeof MagicZoomPlus == "object"){
			MagicZoomPlus.options = {
			'zoom-width':'340',
			'zoom-height':'340',
			'zoom-position':'right',
			'expand-effect':'linear',
			'background-opacity':'50',
			'expand-speed':'200',
			'disable-expand':false,
			'disable-zoom':false,
			'thumb-change':'click',
			'buttons-display':'close',
			'smoothing':'true',
			'smoothing-speed':'40',
			'show-title':'false',
			'opacity-reverse':true }
		}

		// changes the width of the related product table to fix the alignment
		var RealtedTabel = $('#ShopMainLayOutTable .Related_Custom_TBL');
		var RelatedCount = RealtedTabel.find(".ProdListProdHolder").length;
		
		if (RelatedCount == 1){RealtedTabel.attr('width', '25%');}
		if (RelatedCount == 2){RealtedTabel.attr('width', '50%');}
		if (RelatedCount == 3){RealtedTabel.attr('width', '75%');}
	}
	// Shopping cart
	if(pageUrl == ShowBasketUrl){
		$('#ShowBasket_TD .removeBtn:not(:empty) a').click(function(){
			var answer = confirm("Er du sikker du vil fjerne produktet fra kurven?")
			if (!answer)
				return false;			
		});
		
		totalProds = $("#BasketTotalProds").text();
		if(totalProds == "0"){
			$(".OrderButton").click(function(){
				alert("Du har ingen vare i kurven.");
				return false;
			});
			
		}
		
	}
	/*	
	// Tip a friend
	if($('#TipFriend_TD').length){
		// Sætter overskrift på Anbefal
		$('#TipFriend_TD').html('<h1>Anbefal</h1>'+$('#TipFriend_TD').html());
		// Laver brede på table 100%
		findreplace('#TipFriend_TD','400','100%');
		set header "Heading_TipFriend"		
	}
	*/	


	/* :: Common page events :: */
	$.getScript('/includes/basketPopup.js', function() {});

	$('html, body').attr('lang', 'da');

	var $searchField = $("#SearchField");
	$("#Search_Form").submit(function(){
		if($searchField.val() === $searchField.attr("title") || $searchField.val() == ""){
			alert("Du mangler udfylde et søgeord");
			return false;
		}
	});
	$searchField.focusin(function(){
		if($(this).val() == $(this).attr("title")){
			$(this).animate({width:"200px"},300);
			$(this).val("").css("color","#000000");
		}
	}).focusout(function(){
		if($(this).val() == "" || $(this).val() == " "){
			$(this).val($(this).attr("title")).css("color","#999999");
			$(this).animate({width:"120px"},300);
		}
	});
	if($.isFunction($.fn.autocomplete)){
		$searchField.autocomplete(searchwords);
	}
	/*
		$searchField.bind('webkitspeechchange', function(field) {
			var fieldName = $(field.target).attr('name');
			var fieldId = $(field.target).attr('id');
			if ((fieldName == 'q') || (fieldName.indexOf('search') >= 0) || (fieldId.indexOf('search') >= 0) ) {
				field.target.form.submit();
			}
		});	
	*/

	//buy button hover	
	$("#BUYSECTION input[type=image]").hover(function(){
			$(this).attr("src","/images/design/Da/Buttons/f_buybtn_hover.png");
	},function(){
			$(this).attr("src","/images/design/Da/Buttons/f_buybtn.png");
	});

	// x for y a piece price. remove all but the first price.
	$(".ProdListProdHolder").each(function(i){
		$(this).find(".ProdListPriceTable").each(function(j){
			if(!(j === 0))
				$(this).hide();
		});
		
	});

	// If product menu is visible, do menu fixes
	if($("#ProductMenu_Table").is(":visible")){
		$('.SubMenu_Productmenu_Table .SubMenu_Productmenu_Table')
		.parent().parent().addClass('active-cat-open')
		.prev('tr').addClass('active-cat')
		.end().find(".Activ_Productmenu")
		.parent().parent()
		.addClass('active-cat');
		
		if($('.active-cat').length > 1){
		  $('.active-cat:first').addClass("active-cat-parent");
		}		
	}

	// if #map is there load google maps	
	if($("#map").length){
		gMap.init();
	}

	/*
	$('.ProdlistProdImg img').bind('error',(function(){
		$(this).attr({
		  src: 'http://www.frandeli.dk/images/design/icn_noimg-t.png',
		  alt: 'beklager, billede er på vej...'
		});
	});	
	*/
	
	$("#newsletterSubscribeForm input:submit").click(function() {
		newsletter.request("subscribe", {
			ref:'Website',
			form:'#newsletterSubscribeForm',
			email:'#djtdut-djtdut',
			name:'#name',
			onSucces: function(){
				alert("Tak for din tilmelding og interesse i vores nyhedsbrev.");
			}
		});
	});
	$("#newsletterUnsubscribeForm input:submit").click(function() {
		newsletter.request("unsubscribe", {
			ref:'Website',
			form:'#newsletterUnsubscribeForm',
			email:'#email',
			onSucces: function(){
				alert("Du er blevet afmeldt nyhedsbrevet.");
			}
		});
	});

	// Newsletter on order page
	if(pageUrl.indexOf('order1.html') != -1){
		$(".CustomerData_Orderstep1_TBL #Field11_0").after('<tr><td colspan="3">&nbsp;</td></tr><tr><td colspan="3"><label><input id="newsletter" type="checkbox" name="useCMmailList">&nbsp;<b>Ja tak,</b> jeg vil gerne have <b>5% rabat</b> ved næste køb og &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;modtage gode tilbud via nyhedsbrevet.</label></tr>');
		
		$(".SubmitButton_Orderstep1").click(function(){
			if($("#newsletter").is(":checked")){
				newsletter.request("subscribe", {
					ref:'Website',					
					form:'#newsletterSubscribeForm',
					email:'#email',
					name:'#name'
				});
			}
		});
	}

});
