// JavaScript Document
function reload_page(href) {
	document.location.href = href;
}

function searchbox(val) {
	document.location.href = '/search_history/search/' + val;
}

function swap_img(new_img,obj) {
	obj.src = new_img;
}


// AJAX //
function SendForm(formid,element) {	
	$(formid).request({
		evalScripts: true,
		onError: function() { alert('error'); },
		onComplete: function(transport) {
			$(element).innerHTML = transport.responseText;
		}
	})
}


// SCROLABLE CLASS //
function scroll_left(objid) {
	if(!window._offset) window._offset = $(objid).scrollLeft;
	window._offset += 3;
	$(objid).scrollLeft = window._offset;
	
	if(window.timevar) clearTimeout(window.timevar);
	window.timevar = setTimeout('scroll_left("'+objid+'")',10);
}

var Scrollable = Class.create();
Scrollable.prototype = {
  initialize: function(element,SLElement,SRElement,speed) {
    this.element = $(element);
	this.SLElement = $(SLElement);
	this.SRElement = $(SRElement);
    this.active = false;
	this.timer = new Timer(this);
	// set cursor //
	this.SRElement.style.cursor = 'pointer';
	this.SLElement.style.cursor = 'pointer';
	
    this.eventMouseDownL = this.startScroll.bind(this,-speed);
    this.eventMouseDownR = this.startScroll.bind(this,speed);
    this.eventMouseUp   = this.endScroll.bind(this);
    


    Event.observe(this.SRElement, 'mouseover', this.eventMouseDownR);
    Event.observe(this.SLElement, 'mouseover', this.eventMouseDownL);
  },
  startScroll: function(dir) {
    Event.observe(this.SRElement, 'mouseout', this.eventMouseUp);
    Event.observe(this.SLElement, 'mouseout', this.eventMouseUp);

	this.finishCounter = 1;
	this.scrollPoint = 0;
	this.active = true;	
	this.speed = dir;
	this.scroll = this.scrollby.bind(this);
	this.scroll();
  },
  endScroll: function(event) {
	this.active = false;
  },
  scrollby: function() {
  	
	if(this.active) {
		this.element.scrollLeft += parseFloat(this.speed);

		if(this.scroller) this.timer.clearTimeout(this.scroller);
		this.scroller = this.timer.setTimeout("scrollby", 10);
	}
	else {
		images = $$('#'+this.element.id+' img');
		cpoints = Array();
		cpoints[0] = 0;
		for(var i=0; i<images.length; i++) {
			var last = cpoints[i];
			if(!last) last = 0;
			cpoints[i+1] = last + images[i].width + 4;
		}
		for(var i=0; i<cpoints.length; i++) {
			if(this.element.scrollLeft>cpoints[i] && this.element.scrollLeft<cpoints[i+1]) {
				if(this.speed>0) this.scrollPoint = cpoints[i+1];
				else if(this.speed<0) this.scrollPoint = cpoints[i];
				
				if(this.scroller) this.timer.clearTimeout(this.scroller);
				this.scroller = this.timer.setTimeout("scrollFinish", 10);
			}
		}
	}
  },
  scrollFinish: function() {
	this.finishCounter++;
	if( this.element.scrollLeft < this.scrollPoint && this.speed > 0 ) {
		this.element.scrollLeft += parseInt(this.speed);
		if(this.scroller) this.timer.clearTimeout(this.scroller);
		this.scroller = this.timer.setTimeout("scrollFinish", 10);
	}
	else if( this.element.scrollLeft > this.scrollPoint && this.speed < 0 ) {
		this.element.scrollLeft += parseInt(this.speed);
		if(this.scroller) this.timer.clearTimeout(this.scroller);
		this.scroller = this.timer.setTimeout("scrollFinish", 10);
	}
  }
}

// FROM VALIDATION //
function set_shipping_methods(weigth,price,zone) {
	// get zone //
	window.price = parseFloat(price);
	window.zone = zone;
	shipping_options = $('shipping_method').options;
	
	for(var o=shipping_options.length; o>=1; o--) {
		$('shipping_method').remove(o);
	}
	new Ajax.Request('/ajax.php?opt=orders&task=get_shipping',{
		parameters: 'weigth='+weigth+'&price='+price+'&zone='+window.zone,
		onComplete: function(transport) {
			json = transport.responseText.evalJSON();
			
			
			
			json.each(function(s){
				// set options //
				shipping_options = $('shipping_method');
				var opt = document.createElement("option");
				opt.value = s.id;
				if(window.price > parseFloat(s.int_3)) opt.text = s.name + ' - FREE';
				else opt.text = s.name + ' - ' + s.int_1;
				shipping_options.options.add(opt);			
			});
		}
	});
}

function set_form_vals(json,formid) {
	user = json.evalJSON();
	arr = Object.values(user);
	keys = Object.keys(user);
	
	elements =  $(formid).getElements();
	for(var i=0;i<elements.length; i++) {
		for(var j=0; j<keys.length; j++) {
			if((elements[i].name == keys[j] || elements[i].name == 'ship_'+keys[j]) && elements[i].name!='id' && elements[i].name!='name') {
				elements[i].value = arr[j];
			}
		}
		
	}
	
}

var FormValidation = Class.create();
FormValidation.prototype = {
	initialize: function(element) {
		this.element = $(element);
		this.formid = element;
		this.msg = Array();
	    this.options = arguments[1] || {};

		this.requireds = $$('#'+this.formid+' input[class=required]');
		this.requireds2 = $$('#'+this.formid+' input[class="required_marked"]').reduce();
		this.requireds3 = $$('#'+this.formid+' select[class=required]').reduce();
		this.requireds4 = $$('#'+this.formid+' select[class="required_marked"]').reduce();
		this.requireds5 = $$('#'+this.formid+' textarea[class=required]');
		this.requireds6 = $$('#'+this.formid+' textarea[class="required_marked"]').reduce();
		this.requireds = Array(this.requireds,this.requireds2,this.requireds3,this.requireds4,this.requireds5,this.requireds6);
		this.requireds = this.requireds.flatten();
		this.requireds = this.requireds.compact();
		
		button = $$('#'+this.formid+' input[class=button]');
		button.each( function(s) {
			s.style.width = '82px';
		});

		// default data //
		this.valid = true;
		this.element.onsubmit = function() { return false; }
  	 	this.checkForm = this.checkRequired.bind(this);
		
		Event.observe(this.element, 'submit', this.checkForm);
	},
	checkRequired: function() {
		// get required //
		this.valid = true;		
		this.msg = Array();
		
		for(var i=0; i<this.requireds.length; i++) {
			if(!this.requireds[i].value) { 
				this.valid = false;
				// mark required //
				this.requireds[i].className = 'required_marked';
				this.msg[0] = 'Please fill all required fields!';
				//namecol = $('name_'+this.requireds[i].name);
				//namecol.style.color = '#b20000';
			}
			else {
				// unmark required //
				this.requireds[i].className = 'required';
				//namecol = $('name_'+this.requireds[i].name);
				//namecol.style.color = '';
			}
		}
		if(this.options.compare) {
			for(var i=0; i<this.options.compare.length; i++) {
				s = this.options.compare[i];
				obj = $$('#'+this.formid+' input[name='+s+']').reduce();
				obj2 = $$('#'+this.formid+' input[name=confirm_'+s+']').reduce();
				
				if(obj.value!=obj2.value) { 
					this.msg[1] = 'Wrong confirmation'; 
					this.valid = false; 
					obj.className = 'required_marked'; 
					obj2.className = 'required_marked';
				}
				else if(obj.value && obj2.value) {
					obj.className = 'required'; 
					obj2.className = '';
				}
			};
		}
		
		if(this.options.accept) {
			for(var i=0; i<this.options.accept.length; i++) {
				s = this.options.accept[i];
				obj = $$('#'+this.formid+' input[name='+s+']').reduce();
				
				if(obj.checked==false) { this.msg[2] = 'Accept the terms of use.'; this.valid = false; }
			}
		}
		
		if(this.element._pin) this.element._pin.value = '12345';
		
		if(!this.valid) { alert(this.msg.join("\n")); return false; }
		else this.element.submit();
	}
}


function clear_input(obj) {
	obj.value = '';
	obj.onfocus = function() { return false; }
}

// BASCET //
function removee(rid,opt) {
	new Ajax.Request('/ajax.php?opt='+opt+'&task=remove&ids[]='+rid,{
		onComplete: function(transport) {
			// update box //
			new Ajax.Updater('basceet_box','/ajax.php?opt=orders&task=box');
		}
	})
	
}
function add(id,opt) {
	new Ajax.Request('/ajax.php?opt='+opt+'&task=add_to_bascet&ids[]='+id,{
		onComplete: function(transport) {
			// update box //
			new Ajax.Updater('basceet_box','/ajax.php?opt=orders&task=box');
		}
	})
}


// SHOW FLASH //
function swf_insert(filename,w,h) {
			var oeTags = '<object type="application/x-shockwave-flash" data="'+filename+'" width="'+w+'" height="'+h+'" id="VideoPlayback" >'
			+ '<param name="movie" value="'+filename+'" />'
			+ '<param name="allowScriptAcess" value="sameDomain" />'
			+ '<param name="quality" value="best" />'
			+ '<param name="bgcolor" value="#524c4f" />'
			+ '<param name="scale" value="noScale" />'
			+ '<param name="salign" value="TL" />'
			+ '<param name="FlashVars" value="playerMode=embedded" />'
			+ '</object>';
			var oeTagsIE = '<object type="application/x-shockwave-flash" data="'+filename+'" width="'+w+'" height="'+h+'" id="VideoPlayback"  codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0">'
			+ '<param name="movie" value="'+filename+'" />'
			+ '<param name="allowScriptAcess" value="sameDomain" />'
			+ '<param name="quality" value="best" />'
			+ '<param name="bgcolor" value="#524c4f" />'
			+ '<param name="scale" value="noScale" />'
			+ '<param name="salign" value="TL" />'
			+ '<param name="FlashVars" value="playerMode=embedded" />'
			+ '</object>';
		majorVersion=8;
		minorVersion=8;
		installinfo='<div class="get_fla"><a href="https://www.macromedia.com/go/getflashplayer" class="black" target="_blank" ><img src="/images/get_flash.jpg" alt="pobierz Flash Playera" border="0" /><br/></a></div>'; // URL zawierajacy informacje o potrzebie instalacji
		
		if(navigator.product=='Gecko' || navigator.userAgent.indexOf('Opera')!=-2) {
		 if(plugin=navigator.plugins["Shockwave Flash"]) {
		  if(majorVersion > parseInt(plugin.description.substr(plugin.description.indexOf(".")-2, 2))
		  || minorVersion > parseInt(plugin.description.substr(plugin.description.length-2)) )
			document.write(installinfo);  // pobieranie flasha
		  else document.write(oeTags);
		 } else {
			document.write(installinfo);  // pobieranie flasha 
		 }
		}
		else document.write(oeTagsIE);
		//-->
}
