var IE = document.all?true:false

$(document).ready(function() {
	//mouseovers artikelen
	$(".items li").hover(
		function() {
			$(this).addClass('hover');
		},
		function() {
			$(this).removeClass('hover');
		}
	);

	$('.mood .thumbs a').mouseover(function() {
		$('.mood').css('background-image', 'url(' + $(this).attr('href') + ')');
		return false;
	})

	// initialize scrollable 
	$(".scrollgroup:not(.top10 .scrollgroup)").scrollable({ size: 7, clickable: false }).mousewheel().navigator({ navi: 'ul.icons' });
	$(".top10 .scrollgroup").scrollable({ size: 10, clickable: false }).mousewheel().navigator({ navi: 'ul.icons' });
	$(".scrollrelated").scrollable({ size: 3, clickable: false }).mousewheel().navigator({ navi: 'ul.icons' });
	$(".scrolltext").scrollable({ size: 1, clickable: false }).mousewheel().navigator({ navi: 'ul.icons' });

	//Bottom block (o.a. Toplijsten, montage service)
	$(".tabUnit a[rel]").click(function() {
		//Voor selecteren container, op twee niveaus op zoek naar een id.
		var mainId = $(this).parent().attr('id');
		if (!mainId && !$(this).parent().hasClass('tabUnit')) { mainId = $(this).parent().parent().attr('id'); }
		//Alles verbergen
		$(this).parent().parent().find("a[rel]").each(function() {
			if ((mainId != '' && $(this).attr("rel").indexOf(mainId + '_') > -1) || mainId == '') {
				$("#" + $(this).attr("rel")).hide();
			}
		});

		$(".tabUnit a[rel^=" + mainId + "]").parent().removeClass("active");

		//Tonen
		$("#" + $(this).attr("rel")).show();

		//Actief maken
		$(this).parent().addClass("active");
		if($(this).attr("rel")=="top10Articles"){
			$(this).find(".scrollgroup").scrollable({ size: 10 }).mousewheel().navigator({ navi: 'ul.icons' });
		}else{
			$(this).find(".scrollgroup").scrollable({ size: 7 }).mousewheel().navigator({ navi: 'ul.icons' });
		}

		return false;
	});

	//$(".infoicon").tooltip({ cssClass: "tooltip_help", sticky: true });

	$('#zoeken select, #zoeken input').change(
        function() { disableSearchFields($(this)); }
    )

	if ($("#total-price").length > 0) {
		//calculatePrice();
	}
	
	//IE css fix voor uitlijning paging
	if(IE){
		if($('.tabcitems').children('.paging').size()>0){
			$('.tabcitems').addClass('withpaging');
		}
	}
});

function alertStomp(val){
	if(val.toLowerCase().indexOf('stomp')>-1){
		$('#stomp-alert').click();	
	}
}

//accordion detail
function toggleAccordion(o) {
	if (!$(o).parent().find('.box').hasClass('active')) {
		//close current open
		if ($('.box.active').parent().attr('class') == 'option-first') { $('.option-first-space').css('display', 'none'); }
		$('.box.active').slideUp();
		$('.box.active').removeClass('active');
		//open selected
		$(o).parent().find('.box').slideDown();
		if ($(o).parent().attr('class') == 'option-first') { $('.option-first-space').css('display', 'block'); }
		$(o).parent().find('.box').addClass('active');
	}
	return false;
}

function openSearch(o) {
	if($(o).hasClass('open')) {
		$('#search_extended').slideDown();
		$(o).removeClass('open');
		$(o).addClass('close');
} else {
		$('#search_extended').slideUp();
		$(o).removeClass('close');
		$(o).addClass('open');
    }
}

function showHide(id, container) {
	if($('#'+ id).attr('checked')){
	    $('#' + container).css('visibility', 'visible');
	}else{
		$('#' + container).css('visibility', 'hidden');
	}
}

function disableSearchFields(obj) {
    var val = $(obj).val();
    if (val == 'stomp') {
        $('#s_montage input').attr('disabled', 'disabled');
        $('#s_draairichting select').attr('disabled', 'disabled');
    } else {
        $('#s_montage input').attr('disabled', '');
        $('#s_draairichting select').attr('disabled', '');
    }
}

function onEnterDoSearch(e, perma) {
    var k;
    document.all ? k = e.keyCode : k = e.which
    if (k == 13) {
        doSearch(perma);
		return false;
    }
}

function doSearch(perma) {
    if (submit_onclick('frmSearch', false)) {
        var q = '?s=' + $('#s').val();
		if($('#s').val()=='zoeken' || $('#s').val()=='') q = '?s=d' //zoek op alle deuren
        var p = '';
        var o = '';
		var s2 = '';
        var g = '';
        if ($('#search_extended').css('display') == 'block'){
            p = '&p=' + $('#p').val();
			g = '&g=' + $('#g').val();
            $(".searchfields input[name^='o']:checked, .searchfields select[name^='o']").each(function() {
                if ($(this).val() != '') {
                    if (o != '') { o += ',' }
                    o += $(this).val();
                }
            });
			o = '&o=' + o;
			
			$(".searchfields input[name^='s2']:checked, .searchfields select[name^='s2']").each(function() {
                if ($(this).val() != '') {
                    if (s2 != '') { s2 += ',' }
                    s2 += $(this).val();
                }
            });
			s2 = '&s2=' + s2;
        }
        location.href = SITE_URL + perma + q + p + g + o + s2;
    }
}

function ShowMailaFriend() {AnimateThis('mailafriend')}

function AnimateThis(id) {
	if(!IE){ //werkt niet in IE ???
		$('#' + id).animate({opacity: 0}, 1).animate({opacity: 1}, 500);
	}
}

function showMessage(id){
	display('item-'+ id +'-ok','item-'+ id)
	setTimeout("display('item-"+ id +"','item-"+ id +"-ok')",3000)
}

function toggleCheckbox(id, show, hide){
	if($('#'+ id).attr('checked')){
		$('#'+ show).css('display','block');
		if(hide) $('#'+ hide).css('display','none');
	}else{
		$('#'+ show).css('display','none');
		if(hide) $('#'+ hide).css('display','block');
	}
}

// Versie 1.2 (WdS)
function submitNewletterForm(inputId,trueCont,falseCont,wrongCont,path) {
	if(isEmail($('#' + inputId).attr('value'))){
    $.ajax({
        type: "POST",
        url: path + "xml/SubscribeNewsletter?mail=" + $('#' + inputId).attr('value'),
        dataType: "html",
				data: "{}",
        success: function(txt) {            
            if (txt.toUpperCase() == 'TRUE') {
								$('#' + wrongCont).css("display", "none");
                $('#' + trueCont).css("display","block");
                $('#' + falseCont).css("display","none");
            }
            else {
								$('#' + wrongCont).css("display", "none");
                $('#' + trueCont).css("display", "none");
                $('#' + falseCont).css("display", "block");                
            }
        }
    });
	}else{
		$('#' + wrongCont).css("display", "block");
		$('#' + trueCont).css("display", "none");
    $('#' + falseCont).css("display", "none");
	}
}

// Versie 1.2 (JS)
function RemoveSingleViewedArticles(path,id) {
		$.get(path + 'xml/RemoveSingleViewedArticles?id='+id);
		$('#viewedarticles-'+id).html('');
}

// Versie 1.2 (JS)
function RemoveViewedArticles(path) {
    $.get(path + 'xml/RemoveViewedArticles');
    $('#viewedarticles').html('');
}

// Versie 1.2 (WdS)
function updateArticleDetail(articleId, orgSpec1, orgSpec2, htmlCont, path, viewname) {
	if (!viewname) viewname = ""
	
	var result = false;
	var selectedSpec01, selectedSpec02;
	var attributes = getArticleAttributes();

	var amount = 1;
	if ($("#amount-" + articleId).length > 0) {
	    amount = $("#amount-" + articleId).val();
	}

	// disable 'Add to shoppingcart' button
	$("form#shoppingcart").find("INPUT").attr("disabled", "true");

	if (document.getElementById(orgSpec1)) {
		selectedSpec01 = document.getElementById(orgSpec1).options[document.getElementById(orgSpec1).selectedIndex].value;
	} else {
		selectedSpec01 = 0;
	}
	if (document.getElementById(orgSpec2)) {
		selectedSpec02 = document.getElementById(orgSpec2).options[document.getElementById(orgSpec2).selectedIndex].value;
	} else {
		selectedSpec02 = 0;
	}
	//alert(path + 'xml/UpdateArticleDetail?Id=' + articleId + '&spec01Id=' + selectedSpec01 + '&spec02Id=' + selectedSpec02 + "&viewName=" + viewname + "&attributes=" + escape(attributes))
	$.ajax({
		type: "GET",
		url: path + 'xml/UpdateArticleDetail?Id=' + articleId + '&spec01Id=' + selectedSpec01 + '&spec02Id=' + selectedSpec02 + "&viewName=" + viewname + "&attributes=" + escape(attributes) + "&amount=" + amount,
		dataType: "html",
		async: false,
		success: function(html) {
			document.getElementById(htmlCont).innerHTML = html;
			initSIFR();
			result = true;
			$(".scrollrelated").scrollable({ size: 3, clickable: false }).mousewheel().navigator({ navi: 'ul.icons' });
        },
		error: function() {
			result = false;
		}
	});

	//calculatePrice();

	// enable 'Add to shoppingcart' button
	$("form#shoppingcart").find("INPUT").attr("disabled", "false");

	return result;
}

function openBig(url) {
	if (url != '') $('#bigimage').attr('href', url);
	document.getElementById('bigimage').onclick();
}

function showRelatedImg(o, src) {
    var img = o;
    if (src != '') {
        $(img).addClass("active");
        $("#bigRelatedImg").attr("src", src);
        $("#container_info").addClass("hidden");
        $("#container_bigRelatedImg").removeClass("hidden");
        $("#container_bigRelatedImg H2").html($(img).attr("alt"));
    }
}

function hideRelatedImg(o) {
	$(o).removeClass("active");
	$("#container_info").removeClass("hidden");
	$("#container_bigRelatedImg").addClass("hidden");
}

function orderRelated(o) {
    $(o).parents("UL.items").children().each(function() {
        $(this).find("A").removeClass("check");
        $(this).find("INPUT[name^=amount]").val("0");
    });
	$(o).addClass('check');
	$(o).parent().find("INPUT[name^=amount]").val("1");
	calculatePrice();
}

function calculatePrice() {
    var p = parseFloat($('#baseprice').val().replace(",", "."));
    $('[id^=related-price]').each(function() {
        var id = $(this).attr('id');
        id = id.replace('related-price-', '');
        var amount = $('#amount-' + id).val();
        if (amount > 0) p += parseFloat($(this).val().replace(",", "."));
    })
    var priceSplit = p.toFixed(2).split(/\./);
    $('#total-price').html("&nbsp;" + priceSplit[0] + ",<span class=\"sup\">" + priceSplit[1] + "</span>");
}

// Versie 1.3.2 (JS)
function updateArticleFromAddToOrder(articleId, orgSpec1, orgSpec2, htmlCont, path) {
    var selectedSpec01, selectedSpec02
    if (document.getElementById(orgSpec1)) {
        selectedSpec01 = document.getElementById(orgSpec1).options[document.getElementById(orgSpec1).selectedIndex].value
    } else {
        selectedSpec01 = 0
    }
    if (document.getElementById(orgSpec2)) {
        selectedSpec02 = document.getElementById(orgSpec2).options[document.getElementById(orgSpec2).selectedIndex].value
    } else {
        selectedSpec02 = 0
    }
    $.ajax({
        type: "POST",
        url: path + 'xml/UpdateArticleDetail?Id=' + articleId + '&spec01Id=' + selectedSpec01 + '&spec02Id=' + selectedSpec02 + '&viewName=ArticleAddToOrder',
        data: {},
        dataType: "html",
        success: function(html) {            
            $('#' + htmlCont).html(html);
        }
    });
}


function openMessageWindow(s) {
    if (attributesValid(s)) {
        $('#article_ordered').click();
    }
}

function updateMessageWindow(u) {
    $('.highslide-html-content iframe').attr('src', u + '&show=true');
}

// Versie 1.7 (GPS) voor deurshop
function AddRelatedArticlesToOrder(sender, path, checkout_url, related) {
    try {
		var timeout = 0;
		var id = 0;
		var tmpStr = '';

		if (attributesValid(sender)) {

		    //Haal ook de gegevens op van het huidige product
		    var articleId = $('#articleId').val();
		    var articleSpecId = $('#specId').val();
		    var articleAmount = $('#amount-' + articleId).val();
		    var articleAttributes = getArticleAttributes();
		    var articlePrintingText = $('#printingText').val();
		    if (!articlePrintingText) articlePrintingText = '';
		    timeout += 800;
		    $.ajax({
		        type: 'GET',
		        url: path + 'xml/AddToShoppingCart',
		        data: 'articleId=' + articleId + '&amount=' + articleAmount + '&printingText=' + articlePrintingText + '&specId=' + articleSpecId + '&attributes=' + escape(articleAttributes) + '&sequenceMain=True',
		        success: function(html) {

		            // Gerelateerde artikelen
		            $("[name=addToOrder]").each(function() {
		                tmpStr = $(this).attr('id');
		                id = tmpStr.substr(tmpStr.indexOf('-') + 1);

		                var specId = 0;
		                var amount = $('#amount-' + id).val(); 
		                if (amount > 0) {
		                    timeout += 800;
							//aantal zelfde als hoofdartikel
		                    $.ajax({
		                        type: 'GET',
		                        url: path + 'xml/AddToShoppingCart',
		                        data: 'articleId=' + id + '&amount=' + articleAmount + '&printingText=&specId=' + specId + '&sequenceMain=False',
		                        success: function(html) {
		                            document.getElementById('shoppingcart').innerHTML = html;
		                        }
		                    });
		                    //				}
		                }
		            });

		            var currentUrl = $('.highslide-html-content iframe').attr('src');
		            setTimeout("updateMessageWindow('" + currentUrl + "')", timeout);
		        }
		    });
		    //einde ophalen gegevens van het huidige product

		} else {
		    toggleAccordion($('.option-first a'));
		}
		return false;
		
	} catch (err) {
		alert("Er is iets foutgegaan. Probeer het opnieuw door deze pagina te herladen. " + err.message);
	}
}

function expandFlash(bool){
	if(bool){
		$('#container_info').css('display','none');
		$('#container_image').attr('class','articleimage_wide')
	}else{
		$('#container_image').attr('class','articleimage')
		$('#container_info').css('display','block')
	}
}

// Versie 1.7 (JS)
function addCouponCode(val, path) {
	$('#error-coupon').hide();
	$.ajax({
		type: "POST",
		url: path + 'xml/AddCouponCode?typeid=9&code=' + val,
		data: {},
		cache: false,
		dataType: "html",
		success: function(html) {
			if (html == 'True') {
				location.reload(true);
			} else {
				$('#error-coupon').show();
			}
		}
	});
}

// Versie 1.7 (JS)
function removeCouponCode(val, path) {
	$('#error-coupon').hide();
	$.ajax({
		type: "POST",
		url: path + 'xml/RemoveCouponCode?code=' + val,
		data: {},
		cache: false,
		dataType: "html",
		success: function(html) {
			if (html == 'True') {
				location.reload(true);
				
			} else {
				$('#error-coupon').show();
			}
		}
	});
}
