// browser sniffer
var Browser = function(){
  this.uA = navigator.userAgent.toLowerCase();
  this.aN = navigator.appName.toLowerCase();
  this.iE = this.aN.indexOf('microsoft') != -1 ? 1 : 0;
  this.mac =  this.uA.indexOf('mac') != -1 ? 1 : 0;
  this.win = this.uA.indexOf('windows') != -1 ? 1 : 0;
  this.safari =  this.uA.indexOf('webkit') != -1 ? 1 : 0;
  this.opera =  this.uA.indexOf('opera') != -1 ? 1 : 0;
  this.operaMini =  this.uA.indexOf('mini') != -1 ? 1 : 0;
  this.mozilla = this.aN.indexOf('netscape') != -1 && !this.safari ? 1 : 0;
  this.winMozilla = this.mozilla && this.win ? 1 : 0;
  this.winIE = this.iE && this.win && !this.opera ? 1 : 0;
  this.winIE6Down = this.winIE && parseInt(this.uA.split('msie ')[1].substring(0,1)) <= 6 ? 1: 0;
  this.macIE = this.iE && this.mac ? 1 : 0;
};
var browser = new Browser();



// ###################################
// ############## LOADER #############
// ###################################

var Loader = Class({
  actions: [],
  done: false,
  index: 0,
  initialize: function() {
  },
  load: function(){
    var profiler;
    var time;

    if (this.done)
      return;

    this.done = true;
    this.profiler = new Profiler();
    this.next();
  },
  next: function(label, method){
    var loader = this;
    var action = this.actions[this.index++];
    if(!action){
      this.profiler.show();
      return;
    }
    setTimeout(function(){
      var time;
      action.method.bind(window)();
      time = loader.profiler.mark(action.label);
      /*
      if (typeof console != 'undefined')
        console.log(action.label + '(' + time + ')');
      */
      loader.next();
    }, 1);
  },
  schedule: function(label, method, priority){
    var index;
    priority = (priority != undefined) ? priority : Loader.priority.LOW;

    for (index = 0; index < this.actions.length; index++){
      if (this.actions[index].priority > priority)
        break;
    }

    this.actions.splice(index, 0, {
        "label": label,
        "method": method,
        "priority": priority});
  }
});

Loader.priority = {
  HIGH: 0,
  NORMAL: 1,
  LOW : 2 }

var loader = new Loader();

// ###################################
// ############# PROFILER ############
// ###################################

var Profiler = new Class({
  time: 0,
  marks: [],
  initialize: function(){
    this.reset();
  },
  reset: function(){
    this.time = new Date().getTime();
  },
  mark: function(label){
    var time = new Date().getTime() - this.time;
    this.marks.push({
        "label": label,
        "time": time});
    this.reset();
    return time;
  },
  show: function(){
    if(PROFILER) {
      var str = '';
      var total = 0;
      for (var i = 0; i < this.marks.length;i++){
        str += this.marks[i].label + ': ' + this.marks[i].time + '\n';
        total += this.marks[i].time;
      }
      str += '\nTotal: ' + total;
      var el = document.createElement('textarea');
      el.value = str;
      el.style.position = 'absolute';
      el.style.color = '#000';
      el.style.fontSize = '12px';
      el.style.top = '0px';
      el.style.zIndex = '2000';
      el.setAttribute('cols',40);
      el.setAttribute('rows',50);
      el.style.height = '500px';
      document.body.appendChild(el);
    }
  }
});

var PROFILER = 0;

// Use jquery in noConflict mode so we can use Mootools as well
jQuery.noConflict();

// addStyle
var addStyle = function(selector,properties){
  if (document.styleSheets) {
    var s = document.getElementsByTagName('STYLE');
    if (s.length == 0){
      var sheet = document.createElement('style');
      sheet.setAttribute('type','text/css');
      document.getElementsByTagName('HEAD')[0].appendChild(sheet);}
    if (browser.winIE){
      var lastSheet = document.styleSheets[document.styleSheets.length - 1];
      lastSheet.addRule(selector, properties);}
    else {var lastSheet = s[0];
      lastSheet.appendChild(document.createTextNode(selector + ' { ' + properties + ' }'));}
  }
};
addStyle('.drempel','display:none;');

//incl. .js
var jsPath = "/scripts/";
//document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'jquery.corner.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'jquery.scroll.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'jquery.png.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'jquery.thickbox.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'jquery.slideviewer.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'jquery.suggest.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'drivers.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'store.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'switcher.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'range.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'wizard.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'flashobject.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'combobox.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'planner.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'ui.datepicker.js"><\/scr'+'ipt>');

//external links opnen in new window
jQuery.fn.newTarget = function() {
  return this.each(function() {
    //if (this.host != window.location.host) {
    if (this.href && this.host.indexOf(window.location.host) == -1)
	    jQuery.fn.newTarget = function() {
	      jQuery(this).attr('target', '_new');
	    }
  });
};

//toggle input value
jQuery.fn.toggleVal = function() {
return this.focus(function() {
    if( this.value == this.defaultValue ) {
        this.value = "";
        //jQuery(this).addClass(active);
    }
}).blur(function() {
    if( !this.value.length ) {
        this.value = this.defaultValue;
        //jQuery(this).removeClass(active);
        }
    });
};

//toggle div
var togflag = false;
jQuery.fn.toggleDiv = function(id, text1, text2, class1, class2 , parent) {
return this.toggle(function(){
            var el = parent ? jQuery(this).parents(parent).find(id) : jQuery(id);
            jQuery(this).text(text2);
            jQuery(this).removeClass(class1);
            jQuery(this).addClass(class2);
            el.animate({ height: 'toggle' }, "slow");
				    //el.css({ display: "table-row-group" });
            togflag = true;
    },function(){
            var el = parent ? jQuery(this).parents(parent).find(id) : jQuery(id);
            jQuery(this).text(text1);
            jQuery(this).removeClass(class2);
            jQuery(this).addClass(class1);
            el.animate({ height: 'toggle' }, "slow");
				    //el.css({ display: "none" });
            togflag = false;
    });
};

/*/ Disable SRC Zoom
jQuery.fn.toggleZoom = function() {
return this.toggle(function(){
            jQuery(this).animate({ height: '159px', width: '214px' }, "slow");
    },function(){
            jQuery(this).animate({ height: '101px', width: '136px' }, "slow");
    });
}; /* */

//layOut, DOM mods
jQuery.fn.layOut = function(){
    //DOM mods
    jQuery('#columnright').insertBefore('#columnleft');

    // hide h1 if visual is used on shop in shop pages
    if (jQuery('#visual')) {
        jQuery('#columnright').css('top','0');
    }
    jQuery('input[@type=checkbox]').css({border:'none', margin: '0px'});
    jQuery('input[@type=radio]').css({border:'none', margin: '0px'});
    if (!browser.winIE){
        jQuery('input[@type=radio]').css({position: 'relative', top: '3px'});
    }
	 jQuery("table.highlight tr:gt(0)").mouseover(function() {$(this).addClass("over");}).mouseout(function() {$(this).removeClass("over");});
};

/*//radio check tabs
jQuery.fn.radioTabs = function(){
jQuery('.radiotab:checked').parent().css({background:'#F3F3F3 !important'});
return this.click(function(){
        jQuery('.radiotab').parent().css({background:'#FFF !important'});
        jQuery(this).parent().css({background:'#F3F3F3 !important'});
        var tab = jQuery(this).attr("id");
        jQuery('.pane').addClass('drempel');
        jQuery('#pane_'+tab+'').removeClass('drempel');
        alert('#pane_'+tab+'');
    });
};*/

//layout case switcher
var currentLarge = 1;
function checkWindowWidth(){
    var smaller = ((document.documentElement.clientWidth > 0 && document.documentElement.clientWidth < 965) || document.body.clientWidth < 965);
    var elHTML = document.getElementsByTagName('html')[0];
    if (smaller) {
        if (currentLarge == 0){ return; }currentLarge = 0;
        if (elHTML){elHTML.className = 'small'; }
    } else {
        if (currentLarge == 1){ return; } currentLarge = 1;
        if (elHTML){ elHTML.className = ''; }
    }
};

//DOM loader
function init() {
  if (arguments.callee.done) return;
  arguments.callee.done = true;

    checkWindowWidth();

  window.store = new Store();
  jQuery('div.carousel').slideView();

  loader.load();
}

function addThickboxUrls() {
	jQuery('a.thickbox').each(function(index) {
		var href = jQuery(this).attr('href');
		var params;
		//return;
		if (jQuery(this).hasClass('small')) {
			params = "dialog=true&TB_iframe=true&height=250&width=220&modal=true";
		} else if (jQuery(this).hasClass('medium')) {
			params = "dialog=true&TB_iframe=true&height=450&width=660&modal=true";
		} else if (jQuery(this).hasClass('large')) {
			params = "dialog=true&TB_iframe=true&height=450&width=680&modal=true";
		} else if (!jQuery(this).hasClass('link-homeoffer')){
			params = "dialog=true&TB_iframe=true&height=530&width=660&modal=true";
		}

		href += (href.indexOf('?') == -1) ? "?": "&";
		href += params;

		jQuery(this).attr('href', href);
	});
}

loader.schedule("thickbox", function() {
	jQuery('a.thickbox').each(function(index) {
		var href = jQuery(this).attr('href').replace(/height=\d+&/i, '').replace(/width=\d+&/i, '');
		var params;

		if (jQuery(this).hasClass('tb_iframe')) {
			params = "dialog=true&height=530&width=660&modal=true&TB_iframe=true";
		} else if (jQuery(this).hasClass('small')) {
			params = "dialog=true&height=250&width=220&modal=true";
		} else if (jQuery(this).hasClass('medium')) {
			params = "dialog=true&height=400&width=400&modal=true";
		} else if (jQuery(this).hasClass('youtube')) {
			params = "dialog=true&height=440&width=480&modal=true";
		} else if (jQuery(this).hasClass('vl-popup')) {
			params = "dialog=true&height=580&width=660&modal=true";
		} else {
			params = "dialog=true&height=530&width=660&modal=true";
		}

		href += (href.indexOf('?') == -1) ? "?": "&";
		href += params;

		jQuery(this).attr('href', href);
	});

	/// Insert close buttons in the h3's of dialogs
	jQuery('.popup h3, .dialog h3').each(function(index) {
		jQuery(this).append('<a class="close right cancel" href="#">[x]</a>');
	});

	// Attach thickbox close handlers to all 'cancel' elements.
	jQuery('.popup .cancel, body.dialog .cancel').each(function(index) {
		jQuery(this).click(function(event){
			return self.parent.tb_remove();
		});
	});
});

// Add events for clearing birthday inputs onfocus
loader.schedule("birthday-events", function() {
	jQuery("#ipf_geboortedatum_day").focus(function(){
		this.value = this.value == 'dd' ? '' : this.value;
	});
	jQuery("#ipf_geboortedatum_month").focus(function(){
		this.value = this.value == 'mm' ? '' : this.value;
	});
	jQuery("#ipf_geboortedatum_year").focus(function(){
		this.value = this.value == 'jjjj' ? '' : this.value;
	});
});

loader.schedule("misc", function() {
    jQuery('.togglemerken').toggleDiv('.merken','Meer merken','Verberg merken', 'plus', 'min');
    jQuery('.togglebreedte').toggleDiv('.breedtes','Meer breedtes','Verberg breedtes', 'plus', 'min');
    //jQuery('.togglelist').toggleDiv('.section','Toon alle maten','Verberg alle maten', 'plus', 'min', '.shelf');
    //jQuery('.toggle-materials').toggleDiv('.more-materials','Meer','Minder', '', 'down');
    //jQuery('.toggle-add-cilinder').toggleDiv('.add-cilinder','Nieuwe cilinder','Nieuwe cilinder', '', 'down');
    //jQuery('.toggle-add-door').toggleDiv('.add-door','Nieuwe deur','Nieuwe deur', '', 'down');
	 //jQuery('.togglefaq').toggleDiv('.togfaq','Veelgestelde vragen','Veelgestelde vragen', 'minmini', 'plusmini');
    jQuery('a').newTarget();
    jQuery('a.arrowblueup').click(function(){jQuery('body').ScrollTo(800);return false;});
    jQuery('.wbr').replaceWith('<wbr/>');
});

loader.schedule("layout", function() {
  jQuery('html').layOut();
});

loader.schedule("toggles", function() {
  jQuery('input[@name=livesearch]').toggleVal();
  jQuery('input[@name=search]').toggleVal();
  jQuery('textarea').toggleVal();
});

loader.schedule("png fixes", function() {
  jQuery('img[@src$=.png], .actieicon').pngfix();
  jQuery('img[@src$=.png], #panel').pngfix();
});

/*/ Disable zoom
loader.schedule("zoom", function() {
  jQuery('img.zoom').toggleZoom();
});

loader.schedule("product z-index", function() {
    products = jQuery('.product');
    products.each(function(index) {
        jQuery(this).css('z-index', products.length + 100 - index);
    });
});
/* */

loader.schedule("search", function() {
  jQuery("#search .livesearch").suggest({onSelect: function() {
    jQuery("#search form").submit();
  }});
});

loader.schedule("switchers", function() {
  var switchers = new Array();
  jQuery('.switcher').each(function(index) {
    switchers.push(new Switcher(jQuery(this)));
  });
});

loader.schedule("table expand", function() {
  jQuery('.togglelist').click(function(index) {
    var trigger = jQuery(this);
    var section = trigger.parents('.product').find('.section');

    if (section.css('display') == 'none') {
      section.css('display', browser.winIE ? 'block' : 'table-row-group');
      trigger.text('Verberg alle artikelen');
      trigger.removeClass('plus');
      trigger.addClass('min');
    } else {
      section.css('display','none');
      trigger.text('Toon alle artikelen');
      trigger.removeClass('min');
      trigger.addClass('plus');
    }

    return false;
  });
});































loader.schedule("slider", function() {
  // Attach sliders to select elements
  var sliders = new Array();
  jQuery('select.slider').each(function(select){
    sliders.push(new Range($(this)));
  });
});

loader.schedule("misc2", function() {
  try {document.execCommand('BackgroundImageCache', false, true);} catch(e) {};

    // billing on account
    jQuery('.on_account input').focus(function() {
        if (this.value == 'yes') {
            jQuery('#on_account_no_message').removeClass('show');
        } else {
            jQuery('#on_account_no_message').addClass('show');
        }
    });

    // billing terms of payment
    jQuery('.invoice_type input').focus(function() {
        if (this.value == 'grouped') {
            jQuery('.terms_of_payment input').attr('disabled', 'true');
            jQuery('.terms_of_payment').addClass('darkgreytxt');
        } else {
            jQuery('.terms_of_payment input').removeAttr('disabled');
            jQuery('.terms_of_payment').removeClass('darkgreytxt');
        }
    });

    /* filter delete button hover state */
    if (browser.winIE6Down) {
         jQuery('input.delete').hover(
              function () { jQuery(this).addClass('hover'); },
              function () { jQuery(this).removeClass('hover'); }
         );
         jQuery('input.delete.highlight').hover(
              function () { jQuery(this).addClass('hover-highlight'); },
              function () { jQuery(this).removeClass('hover-highlight'); }
         );
    }
});

loader.schedule("SIS Wizard", function() {
    window.wizard = new Wizard();
});

loader.schedule("Planner", function() {
  jQuery('div.planner').each(function(){
    var planner = new Planner(this);
  });

});

loader.schedule("anders", function() {
  jQuery('select[@name=quantity], select.quantity').each(function(){
    jQuery(this).change(function(){
      var select = jQuery(this);
      var container = select.parent();
      if (jQuery(this).css('display') != 'none' && jQuery(this).val() == 'anders'){
        jQuery(this).hide();
		oldname = select.attr('name');
        select.attr('name', '');
        container.append(
            '<div class="custom"><input name="' + oldname + '" class="custom-quantity"><img src="/images/close.gif"></div>');
		jQuery(".custom-quantity", container).focus();
        jQuery('img', container).click(function(){
          jQuery(this).parent().remove();
          select.show();
          select.val(0);
          select.attr('name', oldname);
        });
      }
    });
  });
});

jQuery(document).ready(function(){
  init();
  //jQuery('img').bind('contextmenu', function(e){return false;});

	// Close van Leeuwen popup after adding item to cart
	jQuery(".vl-related-products-cat .cart").click(function(){
		self.parent.tb_remove();
		return false;
	});

	jQuery("#mail-product-link").click(function(){
		form = jQuery("#mail-product")[0];
		var fields = [form.from, form.recipient, form.recipient_email, form.message];
		for (i = 0, el = fields.length; i < el; i++) {
			fields[i].value = '';
		}
		jQuery(form).show();
		jQuery("#tmp-loader").remove();
	});

	jQuery("#mail-product").submit(function(){
		var complete = true;

		var fields = [this.from, this.recipient, this.recipient_email];
		for (i = 0, el = fields.length; i < el; i++) {
			if (fields[i].value) {
				jQuery(fields[i]).removeClass("incomplete");
				continue;
			}

			jQuery(fields[i]).addClass("incomplete");
			complete = false;
		}

		patt = new RegExp(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i);
		if (!patt.exec(this.recipient_email.value)) {
			jQuery(this.recipient_email).addClass("incomplete");
			complete = false;
		}
		else {
			jQuery(fields[i]).removeClass("incomplete");
		}

		if (complete) {
			jQuery(this).hide();
			wrap = jQuery(this).parents('div')[0];
			jQuery(wrap).append('<p id="tmp-loader" class="bordertop"><img src="/images/loader.gif" alt="" /> Uw bericht wordt verzonden..</p>');
			jQuery.ajax({
				'url': '/send_productmail.php',
				'data': {
					'from': this.from.value,
					'recipient': this.recipient.value,
					'recipient_email': this.recipient_email.value,
					'message': this.message.value,
					'product': this.product.value,
					'url': this.product_url.value
				},
				'dataType': 'html',
				'type': 'post',
				'success': function(response) {
					self.parent.tb_remove();
				},
				'error': function(XMLHttpRequest, textStatus, errorThrown){
					alert('Het bericht kon niet verzonden worden.');
				}
			});
		}
		return false;
	});

  /*jQuery("a[@rel='history']").remote('#products_container', function() {
	});
	*/
	//jQuery.ajaxHistory.initialize();
  //jQuery("#TB_window img").bind('contextmenu', function(e){return false;});
});

jQuery(window).unload(function() {
  jQuery('*').unbind();
});

window.onresize = function(){
    checkWindowWidth();
};
