// need to work
// must be in a form with id=form1
// window.addEvent('domready', addeventallFields); must be included on page
// input should have class="validateimage" second word is the type of validation - to add another style add a " " eg: class="validateimage formBGwhite"
// input need id
// submit button needs to be  :<input name="Submit" type="image" src="../images/save.jpg" class="tips" title="Save" />

function checkallFields(){
	failed = 0;	
	//fieldarray = $('input.validate');
	//fieldarray = $('form1').getElements('input[class^=validate]');
	fieldarray = $ES('input[class^=validate]')
	
	fieldarray.each(function(el){
							  
		classtype = el.className;
		
		if(classtype.indexOf(" ") != -1){
		stringarray = classtype.split(" ");	
		classtype = stringarray[0];
		}
		classtype = classtype.replace("validate", "");
		
		if(!validateval(el.id ,classtype)){
			failed++;	
		};
						  
	})
	if(failed < 1){
		$('form1').submit();
	}else{
		
		errordiv = document.getElementById('errormessage');
		if(errordiv != null){
			document.getElementById('errormessage').innerHTML="Please fill in missing fields";
		}
		
	}
 
}

function addeventallFields(){
	failed = 0;	
	theform = $('form1');
	fieldarray = $ES('input[class^=validate]')
	fieldarray.each(function(el){
		el.addEvent("mouseout", function(event){
			checkfield(el)
		})
	});
	fieldarray.each(function(el){
		el.addEvent("keydown", function(event){
			checkfield(el)
		})
	});
	fieldarray.each(function(el){
		el.addEvent("change", function(event){
			checkfield(el)
		})
	});
	if($('form1')){
	var form = $('form1');
		form.addEvent('submit', function(event) {
			var event = new Event(event);
			checkallFields();
			event.stop();
		});
	}
}

function checkfield(el){
	classtype = el.className;
	if(classtype.indexOf(" ") != -1){
	stringarray = classtype.split(" ");	
	classtype = stringarray[0];
	}
	
	classtype = classtype.replace("validate", "");
	
	if(!validateval(el.id ,classtype)){
		failed++;	
	};
}
	
function validateval(ojbid ,type){
	errorcode = 0;
	var ojb = $(ojbid);
	switch(type){
		case "name":
		if(ojb.value == ""){
		errorcode = 9;
		outputerror(ojb, errorcode);
		}
		break; 
		case "txarea":
		if(ojb.value == ""){
		errorcode = 16;
		outputerror(ojb, errorcode);
		}
		break; 
		case "email":
		checkemailaddress(ojb.value)
		if(!IsMatchingEmailAddress(ojb.value)){
			errorcode = 2;
			outputerror(ojb, errorcode);
		}
		break; 
		case "money":
		/* strips any commas*/
		moneyvalue = stripCommas ($(ojbid).value);
		if(!isInteger(moneyvalue)){
			errorcode = 13;
			outputerror(ojb, errorcode);
		}
		if(moneyvalue.length < 4){
			errorcode = 13;
			outputerror(ojb, errorcode);
		}
		break; 
		case "number":
		if(!isInteger(ojb.value)){
			errorcode = 13;
			outputerror(ojb, errorcode);
		}
		if(ojb.value.length < 4){
			errorcode = 13;
			outputerror(ojb, errorcode);
		}
		break; 
		case "date":
		if(!isValidDate(ojb.value)){
			errorcode = 3;
			outputerror(ojb, errorcode);
		}
		break; 
		case "checkbox":
		if(ojb.checked == ""){
			errorcode = 4;
			outputerror(ojb, errorcode);
		}
		break; 
		case "radio":
		if(ojb.value == ""){
			errorcode = 14;
			outputerror(ojb, errorcode);
		}
		break; 
		case "phone":
		phonevalue = stripPhone ($(ojbid).value);
		if(!isInteger(phonevalue)){
			errorcode = 15;
			outputerror(ojb, errorcode);
		}
		if(phonevalue == ""){
		errorcode = 15;
		outputerror(ojb, errorcode);
		}
		break; 
		case "internationalphone":
		if(checkInternationalPhone(ojb.value)){
			errorcode = 6;
			outputerror(ojb, errorcode);
		}
		if(ojb.value == ""){
		errorcode = 1;
		outputerror(ojb, errorcode);
		}
		break; 
		case "image":
		if(!IsMatchingImage(ojb.value)){
		errorcode = 7;
		outputerror(ojb, errorcode);
		}
		break; 
		case "nickname":
		checknickname(ojb.value)
		if(ojb.value == ""){
		errorcode = 10;
		outputerror(ojb, errorcode);
		}
		break; 
		case "password1":
		if(ojb.value == ""){
		errorcode = 11;
		outputerror(ojb, errorcode);
		}
		break; 
		case "password":
		if(ojb.value != $('pass1').value){
		errorcode = 8;
		outputerror(ojb, errorcode);	
		}
		if(ojb.value == ""){
		errorcode = 12;
		outputerror(ojb, errorcode);
		}
		break; 
		default:
		if(ojb.value == ""){
		errorcode = 1;
		outputerror(ojb, errorcode);	
		}
		break; 
	}
	if(errorcode == 0){
	 	outputerror(ojb, 0);
		return true;
	}else{
		return false;
	}
}

function errorlist(num){
	var spaces = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
	error = new Array();
	error[0] = "";
	error[1] = spaces+"Value required.";
	error[2] = spaces+"Please enter a valid email.";
	error[3] = spaces+"Please enter a valid date e.g. yyyy-mm-dd.";
	error[4] = spaces+"Please check box.";
	error[5] = spaces+"Please enter number.";
	error[6] = spaces+"Please enter correct international telephone number.";
	error[7] = spaces+"Select an image.";
	error[8] = "Your Passwords do not match.";
	error[9] = spaces+"Please enter you name";
	error[10] = spaces+"Please enter a nickname";
	error[11] = spaces+"Please enter a password";
	error[12] = spaces+"Please verify your password";
	error[13] = spaces+"Please enter a number to the nearest thousand";
	error[14] = spaces+"Please choose payment method";
	error[15] = spaces+"Enter valid phone number e.g. 028 1234 1234";
	error[16] = spaces+"This field must be completed.";
	return error[num];
}

function IsMatchingImage(str){
    var myImage = /^.*(\.(gif|jpg|bmp|GIF|JPG|BMP))$/;
    return myImage.test(str)
}

function IsMatchingEmailAddress(str){
    var myRegExp = /[a-z0-9-]{1,30}@[a-z0-9-]{1,65}.[a-z]{3}/ ;
    return myRegExp.test(str)
}

function isValidDate(sText) {
		var reDate = /(?:19|20\d{2})\-(?:0[1-9]|1[0-2])\-(?:0[1-9]|[12][0-9]|3[01])/;
        return reDate.test(sText);
}

function outputerror(ojb, errornumber){
	var ojbitem = $(ojb).getParent();
	var ojbitemstyle = $(ojb).getParent().getParent().getParent();
	
	errordiv = $('error'+ojb.id)
	//alert(errordiv)
	if(errordiv == null){
		if(errornumber != 0){
			var errordiv = new Element('div', {'id':'error'+ojb.id}).setStyles('float:left; font-weight:bold; background-image:url(../images/error.jpg); background-repeat:no-repeat; padding:6px 0 4px 0; font-size:11px; color:#FF0000; margin-left:10px;');
			errordiv.setHTML(errorlist(errornumber))
			//$('submit').disabled="disabled";
			errordiv.injectAfter(ojbitem);
			ojbitemstyle.setStyles('color:#FF0000;')
		}
	}else{
		if(errornumber != 0){
			errordiv.setHTML(errorlist(errornumber))
			ojbitemstyle.setStyles('color:#FF0000;')
			//$('submit').disabled="disabled";
		}else{
			errordiv.setHTML("")
			ojbitemstyle.setStyles('color:#000000;')
			//$('submit').disabled="";
		}
	}
}

function stripPhone (numString){
	value = numString;
	value = value.replace(/ /g, "");
    return value;
}

function stringFilter (input) {
				s = input;
				filteredValues = ", "; // Characters stripped out
				var i;
				var returnString = "";
				for (i = 0; i < s.length; i++) { // Search through string and append to unfiltered values to returnString.
				var c = s.charAt(i);
				if (filteredValues.indexOf(c) == -1) returnString += c;
				}
			return returnString; 
}

function stripCommas(numString) {
	value = numString;
	value = value.replace(/,/g, "");
	value = value.replace(/ /g, "");
    return value;
}

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 11;

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone){
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

addhistoryvar = 1;

function changepage(url,id,title){
var fadeonly = new Fx.Style('floater', 'opacity' ,{duration:500}); //animate with no oncomplete

var fadeajax = new Fx.Style('floater', 'opacity' ,{//animate with oncomplete
duration:500,
	//on complete loading page 
	onComplete: function() {
			
		new Ajax(url, {
		method: 'get',
		update: $('floater'),
		evalScripts: true,
		onComplete: function() {
		//on complete fade in using ainmation with on oncomplete
			if(addhistoryvar == 1){
				dhtmlHistory.add('t='+id,title);
			}
			fadeonly.start(0, 1);
		}
	}).request();
	
		}
});
	
	fadeajax.start(1, 0)
	
}


//// ------------------------------- history for ajax --------------------------------------------
function historyChange(newLocation, historyData) {
	window.addEvent('domready', function(){
	
	if(newLocation == 0){
		addhistoryvar = 0;
	}else{
		addhistoryvar = 1;
	}

	if(newLocation != 0){
	hash = getUrlVars(newLocation)
		if(hash.length > 0){
   	otherpage = hash['t'];
		}
	}else{
		hash = getUrlVars()
		if(hash.length > 0){
   	otherpage = hash['t'];
		}
	}
	
	if(otherpage!='' && otherpage!= undefined){
		url = urllinks[otherpage];
		if(url != ''){
			changepage(url);
		}	
	}
		addhistoryvar = 1;
	})
};

function getUrlVars(str){
	var vars = [], hash;
	if(str == undefined){
		if(window.location.href.indexOf('?') > 0){
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		}else{
		var hashes = window.location.href.slice(window.location.href.indexOf('#') + 1).split('&');
		}
	}else{
		var hashes = str.split('&');
	}
	
	for(var i = 0; i < hashes.length; i++){
	hash = hashes[i].split('=');
	vars.push(hash[0]);
	vars[hash[0]] = hash[1];
	}
	return vars;
}

//// ------------------------------- end history for ajax --------------------------------------------

function dragAlbums(){

			var container = $('allcontent');
			$$('.albumCover').each(function(item){
											
			var temp = new Drag.Move(item,{'container': container});
			
			temp.addEvent('onStart', function() {
					item.setStyle('opacity', .5)
					item.style.zIndex = getHighZIndex()+1
				}, true)
				
			temp.addEvent('onComplete', function() {
				if(!window.ie){
					var LoadFade = new Fx.Style(item, 'opacity' ,{duration:500, wait: false});
					LoadFade.start(.5, 1);
				}else{
					item.setStyle('opacity', 1)
				}
				}, true)
			
});

}
var lastzindex = 0;
function getHighZIndex(ojb)
{		
	var i;
	var iHigh = 0;
	
	if(lastzindex == 0){
	albums = $('content').getElements('div[id=pic]')
	//Element.getElementsByClassName("albumCover")
	//--- cycle through all dialogs on page and determine the highest zIndex ---//
	albums.each(function(item) {
		currZ = $(item).style.zIndex;
		if (currZ > iHigh){
			iHigh = currZ;
			lastzindex = currZ;
		}
		
		
		})
	//alert(eval(iHigh)+1)
	//return iHigh;
	}else{
		iHigh = eval(lastzindex)+1;
		lastzindex = iHigh;
	}
	//$('test').setHTML(eval(iHigh)+1);
	ojb.style.zIndex = eval(iHigh)+1;
	
	
}


function showimagesfade(){
	if($('pic')){
	allpic = $$('.divpic');
	
	var myChain = new Chain();
	allpic.each(function(item) { 
		myChain.chain(function(){ 
			fx =  new Fx.Style(item, 'opacity',{duration:500, wait: true});
			fx.start(0, 1);
		}); 
		//alert("running")
		});
		
	var runChain = function() { 
		myChain.callChain();
		if (myChain.chains.length == 0) { runChain = $clear(timer); } 
	}
	var timer = runChain.periodical(100);
	}
	}	
	
function showimagesfadenew(){
	if($('pic')){
	allpic = $$('.divpic');
	
	var myChain = new Chain();
	allpic.each(function(item) { 
		myChain.chain( function(){ 
			fx =  new Fx.Style(item, 'opacity' ,{duration:500, wait: true});
			fx.start(0.05, 1);
		} ); });
	
	var runChain = function() { 
		myChain.callChain();
		if (myChain.chains.length == 0) { runChain = $clear(timer); } 
	}
	var timer = runChain.periodical(50);
	}
	}	



	
function hideimagesfade(){
	if($('pic')){
	allpic = $$('.divpic');
	//alert(allpic.length)
	var myChain = new Chain();
	allpic.each(function(item) { 
		myChain.chain( function(){ 
			fx =  new Fx.Style(item, 'opacity' ,{duration:500, wait: true});
			fx.start(1, 0.05);
		} ); });
	
	var runChain = function() { 
		myChain.callChain();
		if (myChain.chains.length == 0) { runChain = $clear(timer); } 
	}
	var timer = runChain.periodical(50);
	}
}	

Fx.Morph = Fx.Styles.extend({
 
	start: function(className){
 
		var to = {};
 
		$each(document.styleSheets, function(style){
			var rules = style.rules || style.cssRules;
			$each(rules, function(rule){
				//if (!rule.selectorText.test('\.' + className + '$')) return;
				if (!rule.selectorText || !rule.selectorText.test('\.' + className + '$') || !rule.style) return;
				Fx.CSS.Styles.each(function(style){
					if (!rule.style || !rule.style[style]) return;
					var ruleStyle = rule.style[style];
					to[style] = (style.test(/color/i) && ruleStyle.test(/^rgb/)) ? ruleStyle.rgbToHex() : ruleStyle;
				});
			});
		});
		return this.parent(to);
	}
 
});
 
Fx.CSS.Styles = ["backgroundColor", "backgroundPosition", "color", "width", "height", "left", "top", "bottom", "right", "fontSize", "letterSpacing", "lineHeight", "textIndent", "opacity"];


function reflectallimages(){
	//imagearray = $E('#kwicks').getElements('.reflect')
	imagearray = $ES('img[class=product]');
	var myChain = new Chain();
	imagearray.each(function(el) { 					 
		myChain.chain( function(){ efxFactory.reflect($(el),{opacity:1/6}); } ); 
		
	});
	var runChain = function() { 
	myChain.callChain();
		if (myChain.chains.length == 0) { runChain = $clear(timer); } 
	}
	var timer = runChain.periodical(500);
}


function hoverimages(){
	imagearray = $ES('img[class^=product]');
	imagearray.each(function(el){				  
	var product = new Fx.Styles(el.id, {wait: false, duration: 200});
	$(el.id).addEvent('click', function(e){
		new Event(e).stop();
		 window.location = "../products/?ID="+el.id
	});
	$(el.id).addEvent('mouseover', function(e){
		new Event(e).stop();
		if(el.hasClass('product2')){
			product.start('product2_over');
		}else{
			product.start('product_over');
		}
	});
	$(el.id).addEvent('mouseout', function(e){
		new Event(e).stop();
		if(el.hasClass('product2')){
			product.start('product2');
		}else{
			product.start('product');
		}
	});
	}); 
}

function hiderelfection(el,action){
	var productreflect = new Fx.Style('can'+el.id, 'opacity', {duration:500});
	if(!window.ie){
		if(action == 0){
			productreflect.start(1,0);
		}else{
			productreflect.start(0,1);
		};
	}else{
			obj = $('can'+el.id);
		if(action == 0){
			obj.style.display = "none";
		}else{
			obj.style.display = "";
		};	
	}
}

function reflectimages(){
	imagearray = $ES('.productbig');
	imagearray.each(function(el){						  
		$(el.id).addReflection({height:1/8});	
		pngfix(el.id);
	}); 
}

function pngfix(id){
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])
	if ((version >= 5.5) && (document.body.filters)) {
		  var img = document.getElementById(id);
		  var canvas = document.getElementById(id+'can');
		  var imgName = img.src.toUpperCase()
		  if (imgName.substring(imgName.length-3, imgName.length) == "PNG"){
			 var imgID = (img.id) ? "id='" + img.id + "' " : ""
			 var imgClass = (img.className) ? "class='" + img.className + "' " : ""
			 var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
			 var imgStyle = "display:inline-block;" + img.style.cssText 
			 if (img.align == "left") imgStyle = "float:left;" + imgStyle
			 if (img.align == "right") imgStyle = "float:right;" + imgStyle
			 if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
			 var strNewHTML = "<span " + imgID + imgClass + imgTitle
			 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			 + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			 + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
			 var div = new Element('span',{'align': 'center', 'id':img.id ,'class':img.className,'title':img.title}).injectAfter(img);
			 var newimg = document.getElementById(id);
			 canvas.injectAfter(newimg)
		  }
	}
}

	
function callProduct(id, cat){
	if (id){
		Producturl = '../inc/inc.product.php?section='+ cat +'&ID=' + id;
	}else{
		Producturl = '../inc/inc.product.php?section='+ cat +'&ID=0';
	}
	Productlistojb = $('pic'+id).empty().addClass('lbLoading2');
		callv = new Ajax(Producturl, {
			method: 'get',
			update: 'pic'+id,
			evalScripts: true,		
			onComplete: function() {
			Productlistojb.removeClass('lbLoading');
			}
			}).request();
}

function addtobasket(id){
		Producturl = '/inc/addtobasket.php?&ID=' + id;
		callv = new Ajax(Producturl, {
			method: 'get'	
			}).request();
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}
function jumpMenu(selObj,restore){ 
	if(selObj.options[selObj.selectedIndex].id== 'true'){
	  eval("parent.location='/boutique/products/?ID="+selObj.options[selObj.selectedIndex].value+"'");
	}
}

function displayAd(state, image, url){
	if(state == 1){
		var LoadFade1 = new Fx.Styles('content' ,{duration:100});
			LoadFade1.start({
				'opacity':0
			});
		var LoadFade2 = new Fx.Styles('menucontainer' ,{duration:100});
			LoadFade2.start({
				'opacity':0
			});
		var LoadFade3 = new Fx.Styles('mainbody' ,{duration:500});
			LoadFade3.start({
				'opacity':0
			});
		LoadFade3.addEvent('onComplete', function() {
			$('mainbody').style.backgroundImage = 'url('+image+')';
		var LoadFade4 = new Fx.Styles('mainbody' ,{duration:1000});
			LoadFade4.start({
				'opacity':1
			});	
			LoadFade4.addEvent('onComplete', function() {
				window.location = url;
			}, true)	
		}, true)	
	}
}

function addLoadEvent(obj, evType, fn){ 
	if (obj.addEventListener){ 
		obj.addEventListener(evType, fn, false); 
		return true; 
	}else if(obj.attachEvent){ 
		var r = obj.attachEvent("on"+evType, fn); 
		return r; 
	}else{ 
		return false; 
	} 
}
function show(){
	tDiv = "homepage_image";
	if($(tDiv).fx){
		$(tDiv).fx.stop();
	}
	$(tDiv).fx = $(tDiv).effect('opacity', {duration: 3000}).start(1);
}

function callAjax(div, url){
	new Ajax(url, {
		method: 'get',
		update: $(div),
		evalScripts: true,
		initialize: function(){
		this.fx1 = new Fx.Style(div,'opacity', {duration:500});
	},
	onRequest:function(){
		this.fx1.set(0);
	},
	onComplete:function(){
		this.fx1.start(0,1);
	}
	}).request();
}

