
var QUERY_VIEW = 5;
var QUERY_VG = 6;
var QUERY_TYPE = 7
var QUERY_FILTER = 9;
var QUERY_SORT = 10;

// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function initialize_ci_form(use_cookie) {
	if (use_cookie) {
		var mode = get_cookie('ci_mode');
		if (mode == "S") {
			ci_form_shop();
			document.getElementById("shop_button").checked = true;
			document.getElementById("collection_button").checked = false;
			document.getElementById("wish_list_button").checked = false;
		} else if (mode == "W") {
			ci_form_wish_list();
			document.getElementById("shop_button").checked = false;
			document.getElementById("collection_button").checked = false;
			document.getElementById("wish_list_button").checked = true;
		} else {
			ci_form_collection();
			document.getElementById("shop_button").checked = false;
			document.getElementById("collection_button").checked = true;
			document.getElementById("wish_list_button").checked = false;
		}
	} else {
		if (document.getElementById("shop_button").checked) {
			ci_form_shop();	
		} else if (document.getElementById("wish_list_button").checked) {
			ci_form_wish_list();
		} else {
			ci_form_collection();
		}
	}	
}
var cw_readyLoading = false;
function TB_Special(pi_href){
	// get caption: either title or name attribute
	var caption = this.title || this.name || "";
		
	// get rel attribute for image groups
	var group = this.rel || false;
		
	// display the box for the elements href
	if(cw_readyLoading)
		tb_show(caption, pi_href, group);
	else
		setTimeout(function(){TB_Special(pi_href);},1000);
}

jQuery(document).ready(function() {
  cw_readyLoading = true;
});


function TB_showLarge(pi_href, direct){
	var h = jQuery(window).height();
	var w = jQuery(window).width();
	w = w < 750 ? w : 700;
	h = h < 500 ? h : 450;
	pi_href += '&width='+ w + '&height=' + h + (direct ? "&TB_iframe=1" : "");
	if (direct)
		tb_show('', pi_href, '');
	else
		TB_Special(pi_href);
}

function get_viewportsize() {
	var viewportwidth;
	 var viewportheight;

	 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

	 if (typeof window.innerWidth != 'undefined') {
	      viewportwidth = window.innerWidth,
	      viewportheight = window.innerHeight
	 }
	 else if (typeof document.documentElement != 'undefined'
	     && typeof document.documentElement.clientWidth !=
	     'undefined' && document.documentElement.clientWidth != 0)
	 {
	       viewportwidth = document.documentElement.clientWidth,
	       viewportheight = document.documentElement.clientHeight
	 }
	return {w:viewportwidth, h:viewportheight};
}

function TB_showInnerframe(pi_href){
	
	var viewport = get_viewportsize();
	w = viewport.w - 70;
	if (w>1200) w = 1150;
	h = viewport.h - 110;
	pi_href += '&width='+ w + '&height=' + h + "&TB_iframe=1";

	tb_show('', pi_href, '');

}

function TB_showLargeToURL(pi_href, to_url){
	setTimeout(function(){
		var h = jQuery(window).height();
		var w = jQuery(window).width();
		w = w < 750 ? w : 700;
		h = h < 500 ? h : 450;
		TB_Special(pi_href + '?to_url=' + to_url);	
	},100);

}

function queryParameters() {
  var query = document.location.search;
  alert(query);
  var keyValuePairs = query.split(/[&?]/g);
  var params = {};
  for (var i = 0, n = keyValuePairs.length; i < n; ++i) {
    var m = keyValuePairs[i].match(/^([^=]+)(?:=([\s\S]*))?/);
    if (m) {
      var key = decodeURIComponent(m[1]);
      (params[key] || (params[key] = [])).push(decodeURIComponent(m[2]));
    }
  }
  return params;
}


function bulk_add_form(area, locale) {
	
	elements = document.location.pathname.split('/');
	vgid = elements[QUERY_VG];
	type = elements[QUERY_TYPE];
	filter = elements[QUERY_FILTER];
	
	checked = "";
	
	jQuery(".bulk_select").each(function(id) {
		check_box = jQuery(".bulk_select").get(id)
		if (check_box.checked == "1") {
			checked += "&i[" + jQuery(".bulk_select").get(id).id + "]=1"
		}	
	});	
	
	query_parameters = document.location.search;
	if (query_parameters == null || query_parameters == "") {
		query_parameters = "?nofilters=";
	}
	
	if (locale == null || locale == '') {
		locale = "nl";
	}
	
	TB_Special('/' + locale + '/catalog/bulk_add/' + area + query_parameters + '&filter=' + filter + '&type=' + type + '&vg='+vgid + '&height=600&width=600' + checked); return false;
}

function bulk_add_select_all() {
	jQuery(".bulk_select").attr("checked", "checked");
	jQuery(".bulk_select_all").attr("checked", "checked");
	return false;
}

function bulk_add_deselect_all() {
	jQuery(".bulk_select").attr("checked", "");
	jQuery(".bulk_select_all").attr("checked", "");
	return false;
}


function preview_form(id, prefix) {
	if (prefix == null) {
		prefix = "";
	}
	var viewport = get_viewportsize();
	var h = viewport.h - 80;
	var w = viewport.w -120 ;

	w = w > 760 ? w : 760;
	h = h > 510 ? h : 510;
	w = w < 640 ? 640 : w;
	h = h < 400 ? 400 : h;

	TB_Special("/book/" + prefix + "preview/"+id+"?width="+w+"&height="+h); return false;
}

function sample_preview_form(id) {
	preview_form(id, "example_");
}

function toggle_select_boxes(show) {
	if(jQuery.browser.msie && jQuery.browser.version.indexOf('6') == 0){
		jQuery('select').each(function(i){
			this.style.visibility = show ? 'visible' :'hidden';
		});
	}
}

function erase_default_formfields(form) {
	var inputs = form.getElementsByTagName("INPUT");
	for(var i=0; i<inputs.length; i++)
	{
		if (inputs[i].type=="text" && inputs[i].className.indexOf('default_input_text')>=0)
			inputs[i].value = '';
	}
}

function toggle_riskaddress(checkbox) {
	if(checkbox.checked)
		jQuery('#riskaddress').css("display", "none");
	else
		jQuery('#riskaddress').css("display", "block");
}

function update_link_to_bulk_add() {
	
	var user_name = get_cookie('user_name')
	if (user_name == null) {
		// remove_element('bulk_add_link');
	}	
}

function update_shop_and_wish_list_link() {
	// update_vg_parameter_with_current_vg("for_sale_link");
	// update_vg_parameter_with_current_vg("searched_link");
}

function update_vg_parameter_with_current_vg(id, new_value) {
	if(document.getElementById(id)) {
		href = document.getElementById(id).href;
		var elements = href.split('/');
		vg = document.location.pathname.split('/')[QUERY_VG];
		if (vg != null) {
	    	elements[QUERY_VG+2] = document.location.pathname.split('/')[QUERY_VG];
			document.getElementById(id).href = elements.join('/') + window.location.search;
		}	
	}
	
}

function remove_vg_link() {
	var elements = document.location.pathname.split('/');
	vgid = elements[QUERY_VG];
	replace_link('VG' + vgid, '&gt;', null);
}

function remove_standard_or_curiosa() {
	var elements = document.location.pathname.split('/');
	var view = elements[QUERY_VIEW];
	var type = elements[QUERY_TYPE];
	var filter = elements[QUERY_FILTER];
	if (view=='g' || view=='d' || view=='l') {
		var link_id;
		if (type == 's') {
			link_id = 'standard_link';
			hide_field("add_original-drawing");
		} else {
			link_id = 'curiosa_link';
			jQuery("#add_item_link").attr("title", LANG_CURIOSA_TOEVOEGEN);
			change_link("add_item_link",'<img src="/images/add_button_curiosa.gif" alt="'+LANG_CURIOSA_TOEVOEGEN+'" />',"&type=c");
			filter = parseInt(filter);
			unhide_field("add_original-drawing");
		}
		replace_link(link_id, '<strong>', '</strong>');
	} else {
		hide_field("add_original-drawing");
		blank_element('standard_curiosa');
		if (view != 'e') {
			// remove_element('bulk_add');
		}	
	}
}

function change_link(id, new_name, href_postfix) {
	jQuery('#'+id).html(new_name);
	jQuery('#'+id).attr("href", jQuery('#'+id).attr("href") + href_postfix);
}

function replace_link(id, prefix, postfix) {
	prefix = prefix || '';
	postfix = postfix || '';
	var txt = jQuery('#'+id).text();
	jQuery('#'+id).after(prefix+txt+postfix).remove();
}

function blank_element(id) {
	jQuery('#'+id).html('<p>&nbsp;</p>');	
}

function faq() {
	var hash = location.hash.substring(1);
	if (hash != '')
		jQuery('#faq_list h3:not([id="'+hash+'"])').next().css('display', 'none');
	else
		jQuery('#faq_list h3').next().css('display', 'none');
	jQuery('#faq_list h3').each(function() {
		var txt = jQuery(this).text();
		jQuery(this).empty().append(
			jQuery('<a/>').attr('href', '#').text(txt).click(function() {
				jQuery(this).parent().next().slideToggle();
				return false;
			})
		);
	});
	jQuery('a[@href*="#"]').click(function() {
		jQuery(jQuery(this).attr('href')).next().show();
	});
	if (document.location.hash != '') {
		jQuery(document.location.hash).next().show();
		jQuery('html,body').animate({scrollTop: jQuery(document.location.hash).offset().top}, 100);
	}
}

function smoothScroll() {
	jQuery('a[href*=#]').click(function() {
	  if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
	  && location.hostname == this.hostname) {
	    var $target = jQuery(this.hash);
		var h = this.hash;
	    $target = $target.length && $target
	    || jQuery('[name=' + this.hash.slice(1) +']');
	    if ($target.length) {
	      var targetOffset = $target.offset().top;
	      jQuery('html,body')
	      .animate({scrollTop: targetOffset}, 1000,function(){
			document.location.hash = h;
		  });
	     return false;
	    }
	  }
	});
}

function makeImagesClickable() {
	jQuery('.gallery_content .image img').click(function() {
		if (this.parentNode.parentNode.href)
			document.location.href = this.parentNode.parentNode.href;
	});
}
jQuery(document).ready(function() {
	makeImagesClickable();

	
})

function enable_toggler() {
	if(jQuery("div.toggler").length > 0) {
		var $j = jQuery.noConflict();
		$j("div.toggler .short a.toggle_link").click(function(){
			//alert($j(this).parents("div.toggler").html());
			$j("div.toggler div.short").slideDown(0);
			$j(this).parent("div.short").slideUp("fast");
			$j(this).parents("div.toggler").children("div.long").slideDown("fast");
		});
		$j("div.toggler .long a.toggle_link").click(function(){
			$j("div.toggler div.long").slideUp("fast");
			$j(this).parents("div.toggler").children("div.short").slideDown("fast");
		});
		$j("div.toggler a.toggle_link").attr('href', 'javascript:;');
		$j("div.user_list_row").hover(
			function(){
				$j(this).children("span.pop").css({visibility: 'visible'});
			},function(){
				$j(this).children("span.pop").css({visibility: 'hidden'});
			});
		}
		
}

function ci_form_collection() {
	document.getElementById("collected_item_form_fieldset").className = "collection";
	hide_field('selling_price');	
	unhide_field('buying_date');
	unhide_field('buying_price');
	unhide_field('edit_images');
	unhide_field('visible_on_home_page')
	update_field('title_start','Eigen');
	unhide_field('quantity');
}

function ci_form_shop() {
	document.getElementById("collected_item_form_fieldset").className = "shop";
	unhide_field('selling_price');
	unhide_field('buying_date');
	unhide_field('buying_price');
	unhide_field('edit_images');
	unhide_field('visible_on_home_page')
	update_field('title_start','Eigen');
	unhide_field('quantity');
}

function ci_form_wish_list() {
	document.getElementById("collected_item_form_fieldset").className = "wishlist";
	hide_field('selling_price');
	hide_field('buying_date');
	hide_field('buying_price');
	hide_field('edit_images');
	hide_field('visible_on_home_page')
	update_field('title_start','Gezocht');
	hide_field('quantity');
}

function switchBGcolor(n) {
	jQuery('#collection_add fieldset').toggleClass("collection");
	jQuery('#collection_add fieldset').toggleClass("shop");
}

function setStatusColor(choice, row) {
	if (choice.checked) {
		document.getElementById(row).className = "accepted";
	} else {
		document.getElementById(row).className = "rejected";
	}	
}

function update_email(item_id, email, user, title, moderator) {
	email = email.replace(/@@/g,"\n");
	email = email.replace(/@user@/,user);
	email = email.replace(/@title@/,title);
	email = email.replace(/@reason@/,document.getElementById("item_" + item_id + "_reject_reason").value);
	email = email.replace(/@moderator@/,moderator);
	document.getElementById("item_" + item_id + "_email_body").value = email;
}

function toggle_email(choice, row) {
	if (choice.checked) {
		hide_field(row+"_email");
	} else {
		unhide_field(row+"_email");
	}	
}

function hide_fields(element1, element2) {
	hide_field(element1);
	hide_field(element2);
}

function unhide_fields(element1, element2) {
	unhide_field(element1);
	unhide_field(element2);
}

function hide_field(element){
	jQuery("#"+element).css({display:"none"});
}

function unhide_field(element){
	jQuery("#"+element).css({display:"block"});	
}

function update_field(element, text) {
	field = document.getElementById(element)
	if (field != null) {
		field.innerHTML = text;
	}
}

function teaser(column, max_rows) {
	new Ajax.Updater("teaser" + column, "/catalog/teaser/" + column + "/" + Math.floor(Math.random() * max_rows), { method: 'get' });
}

function shop_teaser(max_rows) {
	new Ajax.Updater("shop_teaser", "/catalog/shop_teaser/" + Math.floor(Math.random() * max_rows), { method: 'get' });
}

var rootdomain=document.location.protocol+"//"+window.location.hostname

function user_is_logged_in(){
	var user_name = get_cookie('user_name');

	if (user_name == null || typeof user_name !="string") {
		return false;
	} 
	return user_name;
}

function login_check() {
	var user_name = user_is_logged_in();
	if (user_name===false) {
		hide_field('logged_in');
		unhide_field('not_logged_in');
	}else {	
		unhide_field('logged_in');
		hide_field('not_logged_in');
		
		remove_element('slogan2');
		$j("#login_name").html(user_name);

		if($j("#inbox_link").html().replace(/^\s+|\s+$/,'')=="")
			$j("#inbox_link").html('<a href="/mail" title="" class="user_mail_link"></a>');

	}
}

function piclens_check() {

	if (typeof PicLensLite == "undefined" || !PicLensLite.hasClient()) {
		jQuery("#piclens-available").css({display: 'none'});
		jQuery("#piclens-not-available").css({display: 'block'});
	}	
}

function widget_scope_changed(area, shop) {
	title = document.getElementById("title");
	subtitle = document.getElementById("subtitle");
	
	new_value = document.getElementById("widget_scope").value;
	if (new_value == "S") {
		title.value = shop;
		subtitle.value = area;
	} else if (new_value == "C") {
		title.value = "Mijn Verzameling";
		subtitle.value = area;
	} else {
		title.value = area;
		subtitle.value = "Catalogus";
	}
}

function flash_check() {
	var message = get_cookie('message');
	if (message == null) return;
	
	message = message.replace(/[+]/g," ");
	var type = get_cookie('message_type',"notice");
	if (message != "") {
		document.getElementById("flash_area").innerHTML = '<div id="flash" class="flash_' + type + '"><p>' + message + '</p></div>';
	}
	reset_cookie("message");
	reset_cookie("message_type");
}

function form_check() {
	var user_name = get_cookie('user_name')
	if (user_name == null) {
		//jQuery("#collection_add fieldset div, #collection_add fieldset a").remove();
		//jQuery("#collection_add fieldset ").append('<a href="/user/login">Log in</a> of <a href="/user/register">registreer je gratis</a> om items aan je verzameling, shop of zoeklijst toe te voegen.');
		jQuery("#collection_add form").submit(function(){
			location.href = jQuery("a#login_link").attr("href");
			return false;
		});
	} 
}

function slogan_check() {
	var user_name = get_cookie('user_name')
	if (user_name != null) {
		remove_element('slogan2');
	}	
}

function in_shop() {
	document.getElementById("in_shop").checked = true;
	jQuery("#submitfilter").click();
}

function change_gallery_sort_order(sort) {
	document.getElementById("submitfilter").disabled = true;
	var elements = document.location.pathname.split('/');
	elements.splice(QUERY_SORT,2)
    window.location = elements.join('/') + document.getElementById("sort_selection").value + window.location.search;
}

function go_to_shop_gallery(controller,user,area_id) {
	window.location = "/" + controller + '/go_to_gallery/' + area_id + "?user=" + user;
}

function change_type(area_id) {
	alert("New value: " +  document.getElementById("type_id").value)
	window.location = document.location.pathname + "?area=" + area_id + "&type=c&type_id=" + document.getElementById("type_id").value;
}

function filter_publications() {
	var elements = document.location.pathname.split('/');
	
	var position = QUERY_FILTER
	if (elements[1] == "en") {
		position += 1;
	}
	
	var filter_value = elements[position];
	if (document.getElementById("filter_selection") != null && document.getElementById("filter_selection").checked) {
		filter_value = filter_value ^ 1;
	} else {
		if (filter_value > 1) {
			filter_value = filter_value - 1;
		} else {
			filter_value = 0;
		}
	}	
    elements[position] = filter_value;
    window.location = elements.join('/') + window.location.search;
}

function update_vg(url) {
	window.location = url.replace("vg",document.getElementById("vg_select").value);
}	

function personalise_page(user_name, controller, breadcrumb_text) {
	if (user_name == get_cookie('user_name')) {
		remove_element('bc1_complete');
		jQuery('#bc2').html(breadcrumb_text);
		jQuery('body').attr("class", controller);				
		jQuery('#header_' + controller).attr("class",controller + " active");
		jQuery('#header_explore').attr("class","explore");
	}	
	
}

function remove_element(id) {
	var element = document.getElementById(id);
	if (element == null) return;
	element.parentNode.removeChild(element);	
}

function save_view_location() {
	set_cookie('_catawiki_view', document.location.href, null, null, null, '/');
	//document.cookie = "_catawiki_view=" + document.location.href + "; path=/";
}

function link_to_previous_view(message)  {
	if (message == null) {
		message = "Terug";
	}	
		
	document.write("<a href=\"" + get_cookie("_catawiki_view") + "\">" + message+ "</a>");
}


function home_page_welcome_check(){
	first_visit_check();
}

function first_visit_check() {
	var remove = false;
	var home_or_help_page_visited = (get_cookie('home_or_help_page_visited')=="yes");

	if(user_is_logged_in()!==false) {
		remove = true;
		if(typeof home_or_help != "undefined" && home_or_help) {
			$j(".home_help_button").show();
		}
	} 
	else {
		if(typeof home_or_help != "undefined" && home_or_help) {
			set_cookie('home_or_help_page_visited', 'yes', 2019, 0, 1, '/');
		}
		else if(document.referrer.indexOf("http://"+get_current_domain() + "." + get_current_tld()) == 0) { //binnen de site
			if(home_or_help_page_visited) {
				remove = true;
			}			
		}		 
		else {
			set_cookie('home_or_help_page_visited', 'no', 2019, 0, 1, '/');
		}
	}

	if(remove) { 
		remove_element('first_time');
		remove_element('first_time_explain');
	}	
}

/* http://www.elated.com/articles/javascript-and-cookies/ */
function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
	var options = {};
	options.path = path;
	options.domain = domain;
	options.secure = secure;	
	if (exp_y && exp_m && exp_d) {
		options.expires = new Date(exp_y, exp_m, exp_d);
	}	
	jQuery.cookie(name, value, options);
}
function get_cookie ( cookie_name )
{
	//alert('name: ' + cookie_name + ' - ' + jQuery.cookie(cookie_name));
  return jQuery.cookie(cookie_name);	
}

function reset_cookie(cookie_name) {
	jQuery.cookie(cookie_name, '', {expires: -1, path: '/'});
}

function getQueryString(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

function hide_table_row(id) {
	Effect.DropOut(id);
	remove_element(id);
}

function update_area_column(default_area) {
	area = getQueryString("area",default_area);
	type = getQueryString("type","s");
	new Ajax.Updater("area_column", "/catalogus/Strips-Albumreeksen-HC-1e-reeks-ronde-linnen-rug/a/" + area + "/c/" + type);
}
function click_empty_toggle(input, default_text, focus) {
	if (default_text==null)
		default_text = jQuery(input).attr("default");
//	alert(default_text);

	var $input = jQuery("#"+input.id.replace("[", "\\[").replace("]", "\\]"));
	//alert($input.attr("value"));
	if (focus && (input.value== default_text)) {
//		alert(focus);
		input.value = ''; 
		$input.removeClass('default_input_text');
		//input.className = input.className.replace('default_input_text', '');
	}
	else if (!focus && (input.value=='')) {
		input.value = default_text; 
		$input.addClass('default_input_text');
		//input.className += ' default_input_text'; 
	}
}

function toggle_feedback_pane(name, show) {
	//jQuery('#' + name).css('display', show ? 'block' : 'none');
	if (show)
		jQuery('#' + name).fadeIn("slow");
	else
		jQuery('#' + name).fadeOut("fast");
}

function goto_gallery_page(url, nr) {
	location.href = url.replace('@page@',nr).replace('%40page%40',nr)
}

function handle_enter(inField, e, func, arg1, arg2) {
    var charCode;
    
    if(e && e.which){
        charCode = e.which;
    }else if(window.event){
        e = window.event;
        charCode = e.keyCode;
    }

    if(charCode == 13) {
        func(arg1,arg2);
    }
}
var feedbackTimer;

function add_defaulthandlers_to_inputs() {
	jQuery('form input').each(function(){
		var default_class = "default_input_text";
		 if (this.title.indexOf('||') >= 0) {
				
				default_text = this.title.split('||')[1];
				this.feedback = this.title;
				this.title = '';
				jQuery(this).attr("default", default_text);
				if (this.value=='' || this.value==default_text) {
				  jQuery(this).addClass(default_class);
				  this.value = default_text;
				}
				else 
					jQuery(this).removeClass(default_class);
					
				jQuery(this).keypress(function(e){
					jQuery(this).removeClass(default_class);
				});
				jQuery(this).focus(function(){
						click_empty_toggle(this, null, true);
				});
				jQuery(this).blur(function(){
						click_empty_toggle(this, null, false);
				});
	   }
	});
}

function add_defaulthandlers_to_form(formid) {
	jQuery('#'+formid).submit(function(){
		var default_class = "default_input_text";
		jQuery('#'+formid + ' input.default_input_text').each(function(){
			//alert(jQuery(this).attr('value'));
			jQuery(this).attr('value', ''); 
		});		
	});
}

function add_feedback_to_form() {
	jQuery('fieldset.extended_help input, fieldset.extended_help select, fieldset.extended_help textarea').each(function(i) {
		if(jQuery(this).attr('type') != "file") {	
        	var name = this.id;
			var set_default = false;
	        var default_text="";
	        var default_class = "default_input_text";
	        if (this.title.indexOf('||') >= 0) {
	          	set_default = true;
				default_text = this.title.split('||')[1];
				if (default_text != '') {
					default_text = LANG_BIJVOORBEELD + ": " + default_text;
				}
				this.feedback = this.title;
				this.title = '';
				if (this.value=='' || this.value==default_text) {
				  jQuery(this).addClass(default_class);
				  this.value = default_text;
				}
	        }
			jQuery(this).keypress(function(e){
				jQuery(this).removeClass(default_class);
			});
	        jQuery(this).focus(function() {  

				jQuery(".show_always").each(function(){
						jQuery(this).fadeTo("fast", 0.30);
						clearTimeout(feedbackTimer);
				 });

			  
	          toggle_feedback_pane('feedback_pane_'+name, true);
	          if(set_default)
	            click_empty_toggle(this, default_text, true);
	        });

					jQuery(this).dblclick(function(){
						toggle_feedback_pane('feedback_pane_'+name, false);
			  		feedbackTimer = setTimeout(function(){
									jQuery(".show_always").each(function(){
									jQuery(this).fadeTo("fast", 1);
				 				});
			  		}, 300);
	          if(set_default)
	            click_empty_toggle(this, default_text, false);
					});
	        jQuery(this).blur(function() {  
			
	          toggle_feedback_pane('feedback_pane_'+name, false);
			  		feedbackTimer = setTimeout(function(){
									jQuery(".show_always").each(function(){
									jQuery(this).fadeTo("fast", 1);
				 				});
			  		}, 300);
	          if(set_default)
	            click_empty_toggle(this, default_text, false);
	        });

    	}
	});
}

var exist_timeout;

function add_existquery_to_form(formid, type_id) {
	jQuery('form#'+formid+' fieldset.extended_help:first input.text:first').each(function(i) {//, form#'+formid+' fieldset.extended_help:first select
		if(jQuery(this).attr('type') != "file") {
			jQuery(this).change(function() {
				clearTimeout(exist_timeout);
				exist_timeout = setTimeout(function(){get_existing_items(formid, type_id);}, 800);
			});
			jQuery(this).keypress(function() {
				clearTimeout(exist_timeout);
				exist_timeout = setTimeout(function(){get_existing_items(formid,type_id);}, 800);
			});
		}
	});
}

function get_form_valuemap(formid) {
	return ''+jQuery('#'+formid).serialize();
}

function get_existing_items(formid,type_id) {
	jQuery("div#existing_items").load("/catalog/exists_item?"+get_form_valuemap(formid) + "&typeid=" + type_id, null, function(){fill_existing_items_div();});
}

function fill_existing_items_div() {
	var existingitemsdiv = jQuery("div#existing_items");
	if (existingitemsdiv.html().replace(/^\s+|\s+$/,'') != '') {
		existingitemsdiv.fadeIn("slow");
		add_ei_tooltip();
	}
	else {
		existingitemsdiv.css("display","none");
	}
		
}

function add_ei_tooltip() {
	var anchorpos = jQuery("#existing_items").offset(); 
	if(!document.getElementById('exist_tooltip')) {
		jQuery("#existing_items").append('<div id="exist_tooltip">dfdf</div>'); 
	}
	jQuery("div#existing_items div.cell a").each(function(){
		jQuery(this).attr("tooltiptitle", jQuery(this).attr("title")); 
		jQuery(this).attr("title", "");
	});
	jQuery("div#existing_items div.cell a").hover(
	  			function () {
					jQuery("#exist_tooltip").html(jQuery(this).attr("tooltiptitle"));
					var pos = jQuery(this).offset(); 	
					var width = jQuery(this).width();
					jQuery("#exist_tooltip").css({ "left": (pos.left + width - anchorpos.left) + "px", "top":(pos.top-60) + "px", "display":"block" });	
	  			},
	  			function () {
	  			jQuery("#exist_tooltip").css("display", "none");		
	  			}
	);
}

function toggle_menu_type(id) {
	var listitem = jQuery("#"+id);
	if(listitem.hasClass("open")){
		listitem.removeClass('open');
	}
	else {
		listitem.addClass('open');
	}
}
var widget_timer;
function widget_type_selection(checked, show) {
	clearTimeout(widget_timer);
	if((checked && show) || (!checked && !show)) { 
		jQuery('.optionaloff').fadeOut('fast');
		widget_timer = setTimeout(function(){jQuery('.optionalon').fadeIn('fast');}, 500);
	} 
	else {
		jQuery('.optionalon').fadeOut('fast');
		widget_timer = setTimeout(function(){jQuery('.optionaloff').fadeIn('fast');}, 500);
	}
}

function banner_type_selection(selected_banner_type) {
	if (selected_banner_type == 2) {
		hide_field("image_fields");
		unhide_field("html_fields");
	} else {
		hide_field("html_fields");
		unhide_field("image_fields");
	}	
}		

function toggle_area_selection(selected_filter) {
	if (selected_filter == "A") {
		unhide_field("area_select");
	} else {
		hide_field("area_select");
	}	
}

function reset_field(id) {
	jQuery('#' + id).val('')
}

function selectedValue(selBox) {
  selBox = document.getElementById(selBox);
  return selBox.options[selBox.selectedIndex].text;
}

function select_radio_button(id) {
	jQuery('#' + id).attr("checked","checked")
}

function replace_options(id, new_options,dont_select_first) {
    select_box = jQuery('#' + id);
    select_box.children('option').remove();
    select_box.append(new_options);
	if (dont_select_first != true) {
		select_box.children('option:first').attr('selected','selected');
	} else {
	};	
}	

function select_entry(id, index) {
    select_box = document.getElementById(id);
	select_box.selectedIndex = index;
}	

function show_field_when_checkbox_checked(checked, field) {
	if (checked) {
		unhide_field('level2_grouping');
	} else {
		hide_field('level2_grouping');
	}
}	

function click_radio_button(id) {
	radio_button = document.getElementById(id);
	radio_button.checked = "1";
}

function toggle_selling_price(value) {
	if (value == "S") {
		unhide_field('selling_price');
		unhide_field('composite');
	} else {
		hide_field('selling_price');
		hide_field('composite');
	}
}	

function toggle_review_message(id, value) {
	if (value == "1") {
		unhide_field(id);
	} else {
		hide_field(id);
	}
}

function toggle_review_message_selection(item_id, value) {
	if (value == "1") {
		unhide_field("review_and_freeze" + item_id);
		unhide_field("review_lock" + item_id);
		unhide_field("send_message" + item_id);
	} else {
		hide_field("review_and_freeze" + item_id);
		hide_field("review_lock" + item_id);
		hide_field("send_message" + item_id);
	}
}


function toggle_title_combined_offer(value) {
	if (value == "true") {
		unhide_field('title_combined_offer');
		unhide_field('selling_price_combined_offer');
		hide_field('selling_price_identical_for_all_items');
	} else {
		hide_field('title_combined_offer');
		hide_field('selling_price_combined_offer');
		unhide_field('selling_price_identical_for_all_items');
	}
}	



function toggle_wish_list_info(value) {
	if (value == "W") {
		hide_field('buying_price');
		hide_field('buying_date');
	} else {
		unhide_field('buying_price');
		unhide_field('buying_date');
	}
}	

function numbersonly(e, decimal) {
var key;
var keychar;

if (window.event) {
   key = window.event.keyCode;
}
else if (e) {
   key = e.which;
}
else {
   return true;
}
keychar = String.fromCharCode(key);

if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27) ) {
   return true;
}
else if ((("0123456789").indexOf(keychar) > -1)) {
   return true;
}
else if (decimal && (keychar == "," || keychar == ".")) { 
  return true;
}
else
   return false;
}


function mailUs(nr)
{
	var str ="mail";
	str+="to:";
	if(nr==1) {
		str+="r";
		str+="en";
		str+="e";		
	}
	if(nr==2) {
		str+="m";
		str+="ar";
		str+="c";		
		str+="o";		
	}
	if(nr==3) {
		str+="e";
		str+="r";
		str+="i";		
		str+="k";		
	}
	str+="@c";
	str+="ata";
	str+="w";
	str+="i";
	str+="k";
	str+="i";
	str+=".n";
	str+="l";
	location.href=str;
}
var development = false;
function cw_log(log) {
	if (typeof console == "object" && development)
		console.log(log);
}



//test
/*
Stylish Select 0.3 - $ plugin to replace a select drop down box with a stylable unordered list
http://scottdarby.com/

Copyright (c) 2009 Scott Darby

Requires: $ 1.3

Licensed under the GPL license:
http://www.gnu.org/licenses/gpl.html
*/
(function($){

	//add class of js to html tag
	$('html').addClass('js');

	//create cross-browser indexOf
	Array.prototype.indexOf = function (obj, start) {
		for (var i = (start || 0); i < this.length; i++) {
			if (this[i] == obj) {
				return i;
			}
		}
	}
	
	//utility methods
	$.fn.extend({
		getSetSSValue: function(value){
						if (value){
							//set value and trigger change event
							$(this).val(value).change();
							return this;
						} else {
							return selText = $(this).find(':selected').text();
						}
					},
		resetSS: function(){
						$this = $(this);
						$this.next().remove();
						//unbind all events and redraw
						$this.unbind().sSelect();
					}
	});

	$.fn.sSelect = function(options) {
	  var ie6 = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
		var ie7 = (/MSIE (7)/.test(navigator.userAgent) && navigator.platform == "Win32");
		var ie8 = (/MSIE (8)/.test(navigator.userAgent) && navigator.platform == "Win32");
		return this.each(function(){
			
			var defaults = {
				defaultText: 'Please select',
				animationSpeed: 0, //set speed of dropdown
				ddMaxHeight: '' //set css max-height value of dropdown
			};

			//initial variables
			var opts = $.extend(defaults, options),
				$input = $(this),
				id = $input.attr("id"),
				$containerDivTextWrapper = $('<div class="selectedTxtWrapper"></div>'),
				$containerDivText = $('<div class="selectedTxt"></div>'),
				$containerDiv = $('<div class="newListSelected" tabindex="0"></div>'),
				$newUl = $('<ul class="newList"></ul>'),
				itemIndex = -1,
				currentIndex = -1,
				keys = [],
				prevKey = false,
				newListItems = '',
				prevented = false;
				
			//build new list
			$containerDiv.insertAfter($input);
			$containerDivTextWrapper.prependTo($containerDiv);
			$containerDivText.prependTo($containerDivTextWrapper);
			
			$newUl.appendTo($containerDiv);
			//if ($input.css("width")!="")
			//	$containerDivText.css({width: $input.css("width")});
			
			$input.hide();
			
		
			//test for optgroup
			if ($input.children('optgroup').length == 0){
				//cw_log($input.attr('id'));
				newListItems = "";
				$input.children().each(function(i){
				 	var optiontext = $(this).text();
					// 						//add first letter of each word to array
					keys.push(optiontext.charAt(0).toLowerCase());
					
					newListItems += '<li class="item'+i+'">'+optiontext+'</li>';
					
					 						
					
				});
				//$newUl.append('<li class="item'+'i'+'">'+'dfd'+'</li>');
				//newListItems = $input.html().replace(/<option/g, "<li").replace(/value=/g, "rel=").replace(/<\/option>/g,"</li>");
				
				currentIndex = $input.attr("selectedIndex");
				opts.defaultText = $input.children("option:eq("+currentIndex+")").text();
				
				//add new list items to ul
				$newUl.html(newListItems);
				newListItems = '';
				//cache list items object
				var $newLi = $newUl.children();
								
			} else { //optgroup
				$input.children('optgroup').each(function(i){
				
					var optionTitle = $(this).attr('label'),
						$optGroup = $('<li class="newListOptionTitle">'+optionTitle+'</li>');
						
					$optGroup.appendTo($newUl);

					var $optGroupList = $('<ul></ul>');

					$optGroupList.appendTo($optGroup);

					$(this).children().each(function(){
						++itemIndex;
						var option = $(this).text();
						//add first letter of each word to array
						keys.push(option.charAt(0).toLowerCase());
						if ($(this).attr('selected') == true){
							opts.defaultText = option;
							currentIndex = itemIndex;
						}
						newListItems += '<li>'+option+'</li>';
					})
					//add new list items to ul
					$optGroupList.html(newListItems);
					newListItems = '';
				});
				//cache list items object
				var $newLi = $newUl.find('ul li');
			
			}

			//get heights of new elements for use later
			var newUlHeight = $newUl.height(),
				containerHeight = $containerDiv.height(),
				newLiLength = $newLi.length;
		
			//check if a value is selected
			if (currentIndex != -1){
				navigateList(currentIndex, true);
			} else {
				//set placeholder text
				$containerDivText.text(opts.defaultText);
			}

			//decide if to place the new list above or below the drop-down
			function newUlPos(){
				var containerPosY = $containerDiv.offset().top,
					docHeight = jQuery(window).height(),
					scrollTop = jQuery(window).scrollTop();

					//if height of list is greater then max height, set list height to max height value
					if (newUlHeight > parseInt(opts.ddMaxHeight)) {
						newUlHeight = parseInt(opts.ddMaxHeight);
					}	

				containerPosY = containerPosY-scrollTop;
				if (containerPosY+newUlHeight >= docHeight){
					$newUl.css({top: '-'+newUlHeight+'px', height: newUlHeight});
					$input.onTop = true;
				} else {
					$newUl.css({top: containerHeight+'px', height: newUlHeight});
					$input.onTop = false;
				}
			}

			//run function on page load
			newUlPos();
			
			//run function on browser window resize
			$(window).resize(function(){
				newUlPos();
			});
			
			$(window).scroll(function(){
				newUlPos();
			});

			//positioning
			function positionFix(){
				$containerDiv.css('position','relative');
				doHides();
			}

			function positionHideFix(){
				$containerDiv.css('position','static');
				doShows();
			}
			
			function doHides(){
				if (ie6 || ie7 || ie8)
					$('.view-piclens').addClass("ietobehidden");
				if(ie6) 
					$('select:visible').addClass("ietobehidden");
					
				$('.ietobehidden').css({visibility: 'hidden'});				
			}
			
			function doShows() {
				$('.ietobehidden').css({visibility: 'visible'});
			}
			
			$containerDivTextWrapper.click(function(){
			
				if ($newUl.is(':visible')){
					$newUl.hide();
					positionHideFix()
					return false;
				}

				$containerDiv.focus();
				
					
				
				//show list
				$newUl.slideDown(opts.animationSpeed);
				positionFix();
				//scroll list to selected item
				$newUl.scrollTop($input.liOffsetTop);

			});
			
			$newLi.hover(
			  function (e) {
				var $hoveredLi = $(e.target);
				$hoveredLi.addClass('newListHover');
			  },
			  function (e) {
				var $hoveredLi = $(e.target);
				$hoveredLi.removeClass('newListHover');
			  }
			);

			$newLi.click(function(e){
				var $clickedLi = $(e.target);
				//update counter
				currentIndex = $newLi.index($clickedLi);
				//remove all hilites, then add hilite to selected item
				prevented = true;
				navigateList(currentIndex);
				$newUl.hide();
				doShows();
				
				$containerDiv.css('position','static');//ie
			});

			function navigateList(currentIndex, init){

				//get offsets
				var containerOffsetTop = $containerDiv.offset().top,
					liOffsetTop = $newLi.eq(currentIndex).offset().top,
					ulScrollTop = $newUl.scrollTop();
				
				//get distance of current li from top of list				
				if ($input.onTop == true){
					//if list is above select box, add max height value
					$input.liOffsetTop = (((liOffsetTop-containerOffsetTop)-containerHeight)+ulScrollTop)+parseInt(opts.ddMaxHeight);
				} else {
					$input.liOffsetTop = ((liOffsetTop-containerOffsetTop)-containerHeight)+ulScrollTop;
				}
				
				if(currentIndex==0)
					$containerDivText.addClass("default");
				else
					$containerDivText.removeClass("default");
				
				//scroll list to focus on current item
				$newUl.scrollTop($input.liOffsetTop);
				
				$newLi.removeClass('hiLite')
					.eq(currentIndex)
					.addClass('hiLite');
				var text = $newLi.eq(currentIndex).text();
				//page load
				
		
				//$input.get(0).selectedIn
				//$input.val(text).change();
				
				$input[0].selectedIndex = currentIndex;
				if (init != true){
					$input.change();
				}
				$containerDivText.text(text);
				if(true) {
					if($input.attr("value").indexOf("AZ_") == 0 || $input.attr("value").indexOf("__back") == 0) {
						$input.next(".newListSelected").remove();
						var $loading = $("<div class=\"loading\"><img src=\"/images/loadingfilter.gif\" alt=\"\" /><span>"+LANG_LADEN+"...</span></div>")
						$loading.insertAfter($input);
						var elements = document.location.pathname.split('/');
						var controller = elements[1];
						
						$.ajax({
						   type: "POST",
						   url: "/" + controller + "/filter_options",
						   data: {name: $input.attr('name'), selected: $input.attr("value"), label: $input.get(0).options[0].text, id: $('#area_id').attr("value"), user_id: $('#user_id').attr("value")},
						   success: function(html){
						     $loading.remove();
									reinitFilterByOptions($input, html);
									$me = $("#" + $input.attr("id").replace("[", "\\[").replace("]", "\\]"));
								
								 if (init != true){
								 	setTimeout(function(){$me.next('.newListSelected').find('.selectedTxtWrapper').click();}, 120);
								 }
						   }
						 });
					
					}
				}
			};

			$input.change(function(event){
					$targetInput = $(event.target);
					//stop change function from firing 
					if (prevented == true){
						prevented = false;
						return false;
					}
					$currentOpt = $targetInput.find(':selected');
					currentIndex = $targetInput.find('option').index($currentOpt);
					navigateList(currentIndex, true);
				}
			);
			
			//handle up and down keys
			function keyPress(element) {
				//when keys are pressed
				element.onkeydown = function(e){
					if (e == null) { //ie
						var keycode = event.keyCode;
					} else { //everything else
						var keycode = e.which;
					}
					
					//prevent change function from firing
					prevented = true;

					switch(keycode)
					{
					case 40: //down
					case 39: //right
						incrementList();
						return false;
						break;
					case 38: //up
					case 37: //left
						decrementList();
						return false;
						break;
					case 33: //page up
					case 36: //home
						gotoFirst();
						return false;
						break;
					case 34: //page down
					case 35: //end
						gotoLast();
						return false;
						break;
					case 13:
					case 27:
						$newUl.hide();
						positionHideFix();
						return false;
						break;
					}

					//check for keyboard shortcuts
					keyPressed = String.fromCharCode(keycode).toLowerCase();
					var currentKeyIndex = keys.indexOf(keyPressed);
					if (typeof currentKeyIndex != 'undefined') { //if key code found in array
						++currentIndex;
						currentIndex = keys.indexOf(keyPressed, currentIndex); //search array from current index
						if (currentIndex == -1 || currentIndex == null || prevKey != keyPressed) currentIndex = keys.indexOf(keyPressed); //if no entry was found or new key pressed search from start of array
						navigateList(currentIndex);
						//store last key pressed
						prevKey = keyPressed;
						return false;
					}
				}
			}

			function incrementList(){
				if (currentIndex < (newLiLength-1)) {
					++currentIndex;
					navigateList(currentIndex);
				}
			}

			function decrementList(){
				if (currentIndex > 0) {
					--currentIndex;
					navigateList(currentIndex);
				}
			}

			function gotoFirst(){
				currentIndex = 0;
				navigateList(currentIndex);
			}
			
			function gotoLast(){
				currentIndex = newLiLength-1;
				navigateList(currentIndex);
			}

			$containerDiv.click(function(){
				keyPress(this);
			});

			$containerDiv.focus(function(){
				$(this).addClass('newListSelFocus');
				keyPress(this);
			});
			
			//hide list on blur
			$containerDiv.blur(function(){
			   $(this).removeClass('newListSelFocus');
			   $newUl.hide();
			   positionHideFix();
			});

			//add classes on hover
			$containerDivText.hover(function(e) {
				var $hoveredTxt = $(e.target);
				$hoveredTxt.parent().addClass('newListSelHover');
			  }, 
			  function(e) {
				var $hoveredTxt = $(e.target);
				$hoveredTxt.parent().removeClass('newListSelHover');
			  }
			);

			//reset left property and hide
			$newUl.css('left','0').hide();
			
		});
	  
	};

})(jQuery);

function reinitFilterByOptions($select, optionshtml) {
	
	var id = $select.attr("id");
	var $newselect = jQuery('<select name="'+$select.attr("name")+'" style="'+$select.attr("style")+'">' + optionshtml + '</select>');
	$newselect.insertAfter($select);
	$select.remove();
	$newselect.attr("id", id);
	$newselect.sSelect({ddMaxHeight: '200px'});	
}

jQuery(document).ready(function() {
	var ie6orearlier = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
	//if (!ie6orearlier) {
			jQuery("select.filter").sSelect({ddMaxHeight: '200px'});
				
				
//		}	
});


function gallery_show_user_has_it(item_ids) {
	var ie6orearlier = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
	var baseurl = '/catalog/collected_items';
	var has_it_image_url = "/images/gallery_user_has_it.gif";
	jQuery.getJSON(baseurl, {"ids[]":item_ids},
		function(data) {
	  	for (var i=0;i<data.ids_wish_list.length;i++) {
				jQuery("div#item_" + data.ids_wish_list[i] + " span.in-wish-list img").attr("src", has_it_image_url);
				jQuery("div#item_" + data.ids_wish_list[i] + " span.in-wish-list img").addClass("userhasit");
				jQuery("div#item_" + data.ids_wish_list[i] + " span.in-wish-list").attr("title", LANG_ITEM_OP_JE_ZOEKLIJST);
				jQuery("div#item_" + data.ids_wish_list[i] + " span.in-wish-list img").attr("alt", LANG_ITEM_OP_JE_ZOEKLIJST);
			}
			for (var i=0;i<data.ids_shop.length;i++) {
				jQuery("div#item_" + data.ids_shop[i] + " span.in-shop img").attr("src", has_it_image_url);
				jQuery("div#item_" + data.ids_shop[i] + " span.in-shop img").addClass("userhasit");
				jQuery("div#item_" + data.ids_shop[i] + " span.in-shop").attr("title", LANG_ITEM_IN_JE_SHOP);
				jQuery("div#item_" + data.ids_shop[i] + " span.in-shop img").attr("alt", LANG_ITEM_IN_JE_SHOP);
			}
			for (var i=0;i<data.ids_collection.length;i++) {
				jQuery("div#item_" + data.ids_collection[i] + " span.not-in-collection").attr("class", "in-collection");
				jQuery("div#item_" + data.ids_collection[i] + " span.in-collection img").attr("src", has_it_image_url);
				jQuery("div#item_" + data.ids_collection[i] + " span.in-collection img").addClass("userhasit");
				jQuery("div#item_" + data.ids_collection[i] + " span.in-collection").attr("title", LANG_ITEM_IN_JE_VERZAMELING);
				jQuery("div#item_" + data.ids_collection[i] + " span.in-collection img").attr("alt", LANG_ITEM_IN_JE_VERZAMELING);
			}
		});
}

jQuery(document).ready(function() {
	var protocol = document.location.protocol;
	jQuery.getJSON(protocol+"//"+get_current_domain()+"."+get_current_tld()+"/maintenance.json?"+Math.random(), { }, 		
		function(data){
		if(data) {
			for (var i in data) {
				if(i==locale && data[i].length>0) {
					var $maintanance = jQuery('<div style="height: 0px;height:26px;background:#FF6E2F;border-bottom: 1px solid #ccc; margin-bottom:10px;margin-top:2px;color:white; text-align:center; font-size: 16px;" id="maintainance">'+data[i]+'</div>');
					jQuery('body').prepend($maintanance);	
					jQuery('body').css({padding: 0, margin:0});
				}
			}
		}
	});
});

jQuery(document).ready(function() {
	var hastooltips = false;
	jQuery("a.tooltip").each(function(){
		jQuery(this).attr("htmltitle", jQuery(this).attr("title"));
		jQuery(this).attr("title", "");
		hastooltips = true;
	});
	if(hastooltips) {
		jQuery('body').append("<div id='tooltip'></div>");
		
		jQuery("a.tooltip").hover(function(){
			
			//alert($this.offset());
			var $tooltip = jQuery("#tooltip");
			var $this = jQuery(this);
			$tooltip.html($this.attr("htmltitle"));
			var newleft = $this.offset().left + 20;
			var newtop = $this.offset().top + 20;
			$tooltip.css({left:  newleft+ 'px', top: newtop + 'px'});
			$tooltip.fadeIn("fast");
		}, function(){
			var $tooltip = jQuery("#tooltip");
			$tooltip.fadeOut("fast");
		});
	}
	
});

jQuery(document).ready(function() {
	if($j("form .disable_on_submit").length > 0) {
		var img = new Image();
		img.src = "/images/loading.gif";
	}
	$j("form .disable_on_submit").click(function(){
		$button = $j(this);
		$j(this).parents("form").submit(function(){
			$j("body").addClass("wait");
			$button.addClass("loading_button");
			$button.attr("disabled", "disabled");
		});
	});
});

function get_current_tld(){
	return location.href.split("/")[2].split('.').pop();
}
function get_current_domain(){
	var locarr = location.href.split("/")[2].split('.');
	locarr.pop();
	return locarr.join(".");
}

function update_review_message(id, to, message) {
	if (to == "") {
		mesage = "";
	} else {
		message = message.replace(/CRLF/g,"\n");
		message = message.replace("{{user}}",to);
	}
	update_field(id, message);
}
