//add_to_cart// JavaScript Document

function $(v) { return(document.getElementById(v)); }
function $S(v) { return(document.getElementById(v).style); }


function isValidEmailAddress(emailAddress) {
 		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
 		return pattern.test(emailAddress);
}

function toggle_highlight_byId(allid,idname)
{                      	
	//alert(allid);
	//$(allid).removeClass();   
	          
	$$('#variation_link a').each(function(el) {
		el.setStyle('font-weight', 'normal');
	 //removeClass();
	});    
    	  
	//alert($(allid).getElements('a'));
    //.removeClass();    																																																									
	$(idname).setStyle('font-weight', 'bold');
	//document.getElementById(idname).setAttribute("class", "bold");
}              
  
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
	
/*
function window_teil( url )
{
	window_teil_ = openwindow_center( url, 'teilwindow', 800, 600, 'yes', 'yes' );
	window_teil_.focus();
}
*/

function openwindow_center( url, name, width, height, scrollbars, resizable, menubar )
{
	var left = parseInt( (screen.width - width) / 2 );
	var top = parseInt( (screen.height - height) / 2 );
	
	if( left == NaN || left < 0 ) left = 0;
	if( top == NaN || top < 0 ) top = 0;
	if( scrollbars == undefined ) scrollbars = 'no';
	if( resizable == undefined ) resizable = 'no';
	if( menubar == undefined ) menubar = 'no';
	
	winopen = window.open( url, name, "width="+width+",height="+height+",left="+left+",top="+top+",scrollbars="+scrollbars+",status=no,menubar="+menubar+",toolbar=no,resizable="+resizable);
	
	return winopen;
}

/**
 * Checks/unchecks all tables
 *
 * @param   string   the form name
 * @param   boolean  whether to check or to uncheck the element
 *
 * @return  boolean  always true
 */
function setCheckboxes(the_form, the_field, do_check)
{
    var elts      = document.forms[the_form].elements[the_field];
    var elts_cnt  = (typeof(elts.length) != 'undefined')
                  ? elts.length
                  : 0;

    if (elts_cnt) {
        for (var i = 0; i < elts_cnt; i++) {
            elts[i].checked = do_check;
        } // end for
    } else {
        elts.checked        = do_check;
    } // end if... else

} // end of the 'setCheckboxes()' function

function set_location_href( new_url )
{
	window.location.href = new_url;
	//alert( linktarget );
}
      
function Go(U,T) {
	var Check;
	Check=confirm(T);
	if(Check==true)
		this.location=U;
} 


function change_display( option, value )
{
	if( value == 1 )
	{
		document.getElementById(option + '_button').style.display = 'none';
		document.getElementById(option).style.display = '';
	}
	else
	{
		document.getElementById(option + '_button').style.display = '';
		document.getElementById(option).style.display = 'none';
	}
	set_cookie(option, value);
}

function set_cookie (Bezeichner, Wert) 
{
  var Verfallszeit = 1000 * 60 * 60 * 24 * 365;
  var jetzt = new Date();
  var Auszeit = new Date(jetzt.getTime() + Verfallszeit);
  document.cookie = Bezeichner + "=" + Wert + "; expires=" + Auszeit.toGMTString() + ";";
}

function add_option( select_id, value, name )
{
	var select_element = document.getElementById( select_id );
	
	var opt = document.createElement("option");
	
	opt.text = name;
	opt.value = value;
	var index = null;
  	if (document.all)
    	index = attr.length;
  	select_element.add(opt, index);
}

function add_to_cart(media_id)
{

	//var_material = document.getElementById('material').options[document.getElementById('material').selectedIndex].value;
	//var_format = document.getElementById('formats').options[document.getElementById('formats').selectedIndex].value;
	//var_fit = document.getElementById('fit').options[document.getElementById('fit').selectedIndex].value;
	
	var_material = 1;
	var_format = 1;
	var_fit = 1;
	
	//alert(material + ',' + format + ',' + fit);
	xajax_add_to_cart_x(media_id, var_material + ',' + var_format + ',' + var_fit);
}
function add_to_cart_shop(product_id , reset, quantity, URL)
{      
	xajax_add_to_cart_shop_x(product_id,reset,quantity, URL);
}
   
//set new date
function set_date( new_date , direction, from_limit)
{
	
	switch(direction)
	{
		case 'from':
			
			var to_date = document.getElementById('ruecktermin').value; 
			//Split the todate
			if( to_date.indexOf('/') != -1 )
			{
				to_date_array = to_date.split('/');
			}
			else
			{
				to_date_array = to_date.split('.');
			}
			
			//Split the fromdate :: new_date
			if( new_date.indexOf('/') != -1 )
			{
				new_date_array = new_date.split('/');
				/*
				new_date_array = new Array();
				new_date_array[0] = new_date_array_[2];
				new_date_array[1] = new_date_array_[1];
				new_date_array[2] = new_date_array_[0];
				*/
			}
			else
			{
				new_date_array = new_date.split('.');
			}

		
			break;
			
		case 'to':
			
			var to_date = new_date;
			
			var new_date = document.getElementById('termin').value; 
			//Split the fromdate
			if( new_date.indexOf('/') != -1 )
			{
				new_date_array = new_date.split('/');
			}
			else
			{
				new_date_array = new_date.split('.');
			}
			
			//Split the todate::new_date
			if( to_date.indexOf('/') != -1 )
			{
				to_date_array = to_date.split('/');
			}
			else
			{
				to_date_array = to_date.split('.');
			}
			
			break;
	}
	
	//the same year between from and to
	if( to_date_array.length == 3 && new_date_array.length == 3 )
	{
		load_date = 0;
		if( to_date_array[2] < new_date_array[2] )
		{
			load_date = 1;
		}
		
		if( to_date_array[2] == new_date_array[2] && to_date_array[1] < new_date_array[1] )
		{
			load_date = 1;
		}
		
		if( to_date_array[2] == new_date_array[2] && to_date_array[1] == new_date_array[1] && to_date_array[0] < new_date_array[0] )
		{
			load_date = 1;
		}

		if( load_date == 1 )
		{
				if(direction=='from')
				{
					datum = new Date(new_date_array[2], new_date_array[1] - 1, new_date_array[0]);
					
					ms = datum.getTime() + 7*24*60*60 * 1000;
				}else{
					datum = new Date(to_date_array[2], to_date_array[1] - 1, to_date_array[0]);
					ms = datum.getTime() - 7*24*60*60 * 1000;
				}
				d2 = new Date(ms);
				//alert( d2.toGMTString() );
				year = d2.getYear();
				if( year < 999 )
				{
					year = year + 1900;
				}
				month = d2.getMonth() + 1;
				if( month < 10 )
				{
					month = '0' + month;
				}
				day = d2.getDate();
				//alert( day );
				if( day < 10 )
				{
					day = '0' + day;
				}
				
				//check if the from date reach the limit, then take this limit as from date
				var new_time = ms/1000;
				
				if(direction=='to')
				{
					if( from_limit.indexOf('/') != -1 )
					{
						from_limit_array = from_limit.split('/');
					}
				
					//month/year are the same
					if(from_limit_array[2]==year)
					{
						if(from_limit_array[1]>month || (from_limit_array[0]>day && from_limit_array[1]==month))
						{
							//alert('day_limit: '+from_limit_array[0]+' day: '+day+' month_limit: '+from_limit_array[1]+' month: '+month);
							day = from_limit_array[0];
							month = from_limit_array[1];
						} 
						
						var new_date = day+'/'+month+'/'+year;
						document.getElementById('termin_time').value = new_time;
						document.getElementById('termin').value = new_date;
						eval(xajax_print_cat_cal(new_time,'from',1,'',new_time));
						 
					}
						 
				}else{
				
					var new_date = day+'/'+month+'/'+year;
					document.getElementById('ruecktermin_time').value = new_time;
			
					document.getElementById('ruecktermin').value = new_date;
					eval(xajax_print_cat_cal(new_time,'to',1,'',new_time));
				 
				} 	
		}
	}
	
	
	//alert(return_date);
	//alert(new_date);
	//alert(rtdate_array[0]);
					
}
function submit_to_ajax(formname, x_func, x_params)
{
	var tmp_str = '';
	
	for(i=0;i<document.forms[formname].elements.length;i++)
	{	
		switch(document.forms[formname].elements[i].type)
		{
			
			case 'checkbox':
				if(document.forms[formname].elements[i].checked === true)
				{
					tmp_str += document.forms[formname].elements[i].id + '~xx~' +document.forms[formname].elements[i].value + '**YY**';
				}
				break;
				
			case 'radio':
				if(document.forms[formname].elements[i].checked === true)
				{
					tmp_str += document.forms[formname].elements[i].name + '~xx~' +document.forms[formname].elements[i].value + '**YY**';
				}
				break;
		
			default:	
				tmp_str += document.forms[formname].elements[i].id + '~xx~' +nl2br(document.forms[formname].elements[i].value) + '**YY**';
				break;
		}
		//alert(tmp_str);
	}
	if(document.forms['item_edit_form'])
	{
		for(i=0;i<document.forms['item_edit_form'].elements.length;i++)
		{
			if(document.forms['item_edit_form'].elements[i].type == 'checkbox')
			{
				if(document.forms['item_edit_form'].elements[i].checked === true)
				{
					tmp_str += document.forms['item_edit_form'].elements[i].id + '~xx~' +document.forms['item_edit_form'].elements[i].value + '**YY**';
				}
				
			}
			else
			{
				tmp_str += document.forms['item_edit_form'].elements[i].id + '~xx~' +nl2br(document.forms['item_edit_form'].elements[i].value) + '**YY**';
			}
		}
	}
	eval('xajax_' + x_func + '("' + x_params + '","' + tmp_str + '")');
}
function nl2br (str, is_xhtml) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Philip Peterson
    // +   improved by: Onno Marsman
    // +   improved by: Atli Þór
    // +   bugfixed by: Onno Marsman
    // *     example 1: nl2br('Kevin\nvan\nZonneveld');
    // *     returns 1: 'Kevin<br />\nvan<br />\nZonneveld'
    // *     example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
    // *     returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
    // *     example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
    // *     returns 3: '<br />\nOne<br />\nTwo<br />\n<br />\nThree<br />\n'
 
    breakTag = '<br />';
    if (typeof is_xhtml != 'undefined' && !is_xhtml) {
        breakTag = '<br>';
    }
 
    return (str + '').replace(/([^>]?)\n/g, '$1'+ breakTag);
}
function toggle_display_radio(act_obj, objs)
{

	objs_array = objs.split('-');
    for(i=0;i < objs_array.length; i++){
		if(objs_array[i]==act_obj)
		{
			document.getElementById(act_obj).style.display = 'block';
		}else{

			document.getElementById(objs_array[i]).style.display = 'none';
		}
	}
}

function toggle_display(obj)
{
	mainobjs = obj.split('+');
	if( mainobjs.length == 2)
	{
		document.getElementById(mainobjs[0]).style.display = 'block';
		objs = mainobjs[1].split('-');
	    for(i=0;i < objs.length; i++){
            document.getElementById(objs[i]).style.display = 'none';
        }
	}
	else
	{
		objs = obj.split('-');
	    for(i=0;i < objs.length; i++){
			 if (document.getElementById(objs[i]).style.display == 'block' || document.getElementById(objs[i]).style.display == '')
	         {
	                 document.getElementById(objs[i]).style.display = 'none';
	         }
	         else
	         {
	                 document.getElementById(objs[i]).style.display = '';
	         }
         }
	}
}
function toggle_options(obj,ID)
{
	if((obj.selectedIndex+1) == obj.options.length)
         {
         	document.getElementById(ID).style.display = 'inline';
         }
	else
         {
         	document.getElementById(ID).style.display = 'none';
         }
}

// used for menu in 004
navtime = setTimeout("undo_menu()",1000);
function do_menu(key)
{
	for(i=0; i<6; i++)
	{
		if(document.getElementById(i)!=null)
		{
			document.getElementById(i).style.display='none';
		} 
	}
	document.getElementById(key).style.display='block';
}
function undo_menu()
{
	for(i=0; i<6; i++)
	{
		if(document.getElementById(i)!=null)
		{
			document.getElementById(i).style.display='none';
		}
	}
}
function check_menu()
{
	if(navtime)
	{
		clearTimeout(navtime);
	}
}

var countlines = 1;
function add_line(fieldnames,target_obj)
{	
	for(i=0; i < fieldnames.length; i++)
	{
		var obj = document.getElementById(fieldnames[i]+"[0]").cloneNode(true);
		obj.id = fieldnames[i]+"["+countlines+"]";
		obj.name = fieldnames[i]+"["+countlines+"]";
		obj.value = "";
		document.getElementById(target_obj).appendChild(obj);
	}
	countlines++;
	document.getElementById('countlines').value = countlines;
}

function toggle_status(name_str,default_class,count,id)
{
	for(i=0;i<count;i++)
	{
		document.getElementById(name_str + i).className = default_class;
	}
	document.getElementById(name_str + id).className = default_class +'_active';
}
// used for menu in 004

function dsp_page(page_url, result_container)
{
	//alert(page_url+' --> '+result_container);
	$('#'+result_container).load(page_url).fadeIn();
	$.scrollTo('#logo');

}


function checkForm(formname)
{
// This is copied form backend !
	err = false;
	//Before: have to clear error label created by jquery.Validation
	if( $('#form_'+formname+' label.error').length > 0)		
	{
			$('#form_'+formname+' label.error').each(function(){
				$('#form_'+formname+' label.error').remove();  
			});	
		err  = true;			//as long as there are validate error -> not send form
	}
	
	//check register on merchant registratiwon only
	if(formname =='merchant_register' && $('#form_merchant_register .error').length > 0)		
	{
		err = true;			//as long as there are validate error -> not send form
	}
	
	
	$("#message").html('');
	$(".error").removeClass("error");
	var counter = 0;
	$('#form_'+formname+' .mandatory').each(function(index) {
		
		if($(this).val() == "" || $(this).val()==null || $(this).val() == "" &&  ($(this).attr("error")==1))
		{
			$(this).addClass("error");
			$(this).attr("error","1");
			err  = true;
			 
			if($(this).attr("name") == "img_uploaded")
			{
				$("#message").html('<div class="error">Please upload an image!</div>');
			}
			
			if(counter==0)
			{   
				if($(this).attr("class").match("tiny"))
				{
					$('#'+$(this).attr("name")+'_tbl').attr('style','border: 1px solid red;');	
					global_oldcurrentTagName = $(this).attr("name");
				}else{ 
					$('#'+global_oldcurrentTagName+'_tbl').attr('style','border: 0px solid red;');	
				}
				$.scrollTo($(this), 800);
				//alert($(this).attr('name'));
			} counter++;  
		}
		if( $(this).attr("type") == "checkbox" && $(this).attr("checked") === false )
		{
			if($(this).attr("name")=='agree' && $('#read_agb').length > 0)
			{
				$('#read_agb').addClass('error');
			}
			$("#errdiv_"+$(this).attr("name")).addClass("error");
			err  = true;
			if(counter==0)
			{   
				if($(this).attr("class").match("tiny"))
				{
					$('#'+$(this).attr("name")+'_tbl').attr('style','border: 1px solid red;');	
					global_oldcurrentTagName = $(this).attr("name");
				}else{ 
					$('#'+global_oldcurrentTagName+'_tbl').attr('style','border: 0px solid red;');	
				}
				$.scrollTo($(this), 800); 
			} counter++;
			
		}
	});
	switch(formname)
	{
		case 'stuff_register':
		case 'stuff_paynow':
			if(err==false)
			{
				err = checkCCDate();
			}
			
		break;
	}

	$('#form_'+formname+' .confirm').each(function(index) {
		tmp = $(this).attr("id").split('_');
		err = checkConfirm(tmp[0]);	
	});  
	if(err==true){
		if($('#member_error').length > 0)
		{
			$('#member_error').show();
		}
	}
	return err;
}



	function show_image(url)
	{

		$("div.galery_stage").fadeIn("slow");
		$("div.galery_big_image").fadeIn("slow");
		$("div.galery_big_image").append(document.createElement("img"));
		$("div.galery_big_image img").attr("src",url);
		$("div.galery_big_image").css('top', $(window).height()/2-280+getScrollXY());
		
		$("div.galery_big_image img").click(function(){
			$("div.galery_stage").fadeOut(1);
			$("div.galery_big_image").fadeOut(1);
			$("div.galery_big_image").html('');
		});
		$("div.galery_big_image").click(function(){
			$("div.galery_stage").fadeOut(1);
			$("div.galery_big_image").fadeOut(1);
			$("div.galery_big_image").html('');
		});


		
		

	}
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return scrOfY ;
}


	var activearea = 'spacerarea';
	var leftpos = 0;
	moveright = 0;
	var act_var_img = false;
	
	
	function show_tell_a_friend(product_id,recipient)
	{
		if(typeof(recipient) == "undefined")
		{
			recipient = '';
		}
		$('#blender').height($(document).height()).fadeIn().css('z-index',99999999);		
        newTop = $(window).scrollTop() + ($(window).height() - 600) / 2;
        $("#tell").css("top", newTop + "px").css('z-index',99999999);	
		$('#tell').load('/index.php?page=app|tell_a_friend&product_id='+product_id+'&amp;recipient='+recipient).fadeIn();
	
	}	
	
	function highlight_var_img(id)
	{
		if(act_var_img != false)
		{
			document.getElementById('thumb'+act_var_img).className = 'gal_inactive';
		}
		document.getElementById('thumb'+id).className = 'gal_active';
		act_var_img = id;		
	}
	
	function slide_right(count,slideid)
	{

		if( leftpos < (58*count-450)*-1)
		{	
			clearInterval(moveright);
			document.getElementById('img_slide_right_1').src='../files/css/008/a/spacer.gif';
		} 
		else
		{
			leftpos -=1;
			document.getElementById('innerslide'+slideid).style.marginLeft = leftpos+'px';
			document.getElementById('img_slide_left_1').src='../files/css/008/a/skip-left-1.gif';
			
		}


	}
	
	function slide_left(slideid)
	{
		if( leftpos == 0)
		{    
			clearInterval(moveright);
			document.getElementById('img_slide_left_1').src='../files/css/008/a/spacer.gif';
		}
		else
		{
			leftpos +=1;
			
			document.getElementById('innerslide'+slideid).style.marginLeft = leftpos+'px';
			document.getElementById('img_slide_right_1').src='../files/css/008/a/skip-right-1.gif';
			
		}

	}
	function start_slide(direction, count, slideid)
	{
	
		if(direction =='right')
		{

			moveright = setInterval("slide_right("+count+","+slideid+")",10);

		}
		else
		{
			moveleft = setInterval("slide_left("+slideid+")",10);
		}

	}

	function submit_login_form_popup()
	{
		var popup_error = 0;
		if($('#login_form_popup #login_email').val() == "")
		{
			$('#login_form_popup #login_email').addClass('error');
			popup_error = 1;
		}
		if($('#login_form_popup #login_password').val() == "")
		{
			$('#login_form_popup #login_password').addClass('error');
			popup_error = 1;
		}
		if(popup_error == 0)
		{
			$('#login_form_popup').submit();
		}
	}
	
	var selected_samples = new Array();
var selected_samples_images = new Array();
var selected_samples_title = new Array();
Array.prototype.contains = function(obj) {
     var i, listed = false;
     for (i=0; i<this.length; i++) {
       if (this[i] === obj) {
         listed = true;
         break;
       }
     }
     return listed;
   };
   
   
   
   function a_s(this_id,id,remove)
{
	var title = "";
	
	if(false === selected_samples.contains(this_id) && 1 != remove)
	{	
		selected_samples.push(this_id);
		selected_samples_images.push(id);
		if(document.getElementById('img_id_'+id))
		{
			title = document.getElementById('img_id_'+id).getAttribute("title");
		}
	 
		selected_samples_title[id] = title;
	}

	if( 1 == remove)
	{
		selected_samples_1 = selected_samples.slice(0,this_id);
		selected_samples = selected_samples_1.concat(selected_samples.slice(this_id+1));
		selected_samples_images_1 = selected_samples_images.slice(0,this_id);
		selected_samples_images = selected_samples_images_1.concat(selected_samples_images.slice(this_id+1));
	}
	
		var container = '';
		for(i = 0; i < selected_samples.length; i++)
		{
			container += '<img class="cursor" title="'+selected_samples_title[selected_samples_images[i]]+'" alt="'+selected_samples_title[selected_samples_images[i]]+'" src="/media.php?ID='+selected_samples_images[i]+'&folder=thumb" onClick="a_s('+i+','+i+',1)">';
		}
		document.getElementById('selection').innerHTML = container;

	document.forms.material_form.cm_samples.value = selected_samples.join(',');
}


function toggle_filter(filter)
{
	$("#div_"+filter).animate({
		"height": "toggle", "opacity": "toggle"
	}, { duration: "fast" });
	switch(filter){
		case "currency_sel":
			hide_currency_sel = setTimeout("$('#div_currency_sel').fadeOut(200)",1500);
		break;
		case "lang_sel":
			hide_lang_sel = setTimeout("$('#div_lang_sel').fadeOut(200)",1500);
		break;
	}
}






