 Event.addBehavior({
      "form.validate:submit" : function(event) { return checkRequiered(this); }
 });




function highlightRequiered(id, message){
	$(id).style.color = "black"
	$(id).value = message
	new Effect.Highlight(id,{afterFinish: function(){$(id).value="";$(id).style.color = ""}})
}
function isValidEmail(str) {
   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
 }

function signup(){
	readytosend = "yes"

	if($F('name')==""){
		highlightRequiered('name', "Required")
		readytosend = "no"
	}
	if($F('email')=="" || !isValidEmail($F('email'))){
		highlightRequiered('email', "Required")
		readytosend = "no"
	}
	if(readytosend == "yes"){
		var url = '/modules/members/signup.php';
		var pars = Form.serialize($('signupform'))
		//var SignupAjax = new Ajax.Updater('inside', url, {method: 'get', parameters: pars});
		
		
/*		var myAjax = new Ajax.Request(
			url, 
			{
				method: 'post', 
				parameters: pars, 
				evalScripts: true,
				onComplete: UpdateInside
			});*/
			
			
			
			
			var myAjax = new Ajax.Updater(
			'inside', url, 
			{
				method: 'post', 
				parameters: pars, 
				evalScripts: true,
				onComplete: UpdateInside
			});
	}
}
function UpdateInside(originalRequest){
	$('inside').style.display = "none"
	//$('inside').innerHTML =originalRequest.responseText;
	Effect.Appear('inside', {duration: 1.6, queue:{scope:'inside', position:'end'}});


}

function Set_Cookie(name, value, expires, path, domain, secure ) {

	//alert("Setting Cookie on "+name+": "+value);

	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	if ( expires ){
		//expires = expires * 1000 * 60 * 60 * 24;
		expires = expires * 1000 * 60 * 60;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}
function Get_Cookie( name ) {
		
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
	return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
	
function logout(){
	Delete_Cookie( "member_login", "/")

	var url = '/modules/members/signup_form.php';
	var myAjax = new Ajax.Updater(
			'inside', url, 
			{
				method: 'post', 
				evalScripts: true,
				onComplete: UpdateInside
			});
}
/* Cookies */

var Cookie = {
	set: function(name,value,seconds){
		if(seconds){
			d = new Date();
			d.setTime(d.getTime() + (seconds * 1000));
			expiry = '; expires=' + d.toGMTString();
		}else
			expiry = '';
		document.cookie = name + "=" + value + expiry + "; path=/";
	},
	get: function(name){
		nameEQ = name + "=";
		ca = document.cookie.split(';');
		for(i = 0; i < ca.length; i++){
			c = ca[i];
			while(c.charAt(0) == ' ')
				c = c.substring(1,c.length);
			if(c.indexOf(nameEQ) == 0)
				return c.substring(nameEQ.length,c.length);
		}
		return null
	},
	unset: function(name){
		Cookie.set(name,'',-1);
	}
}




/* Form Functions */
 
function AjaxForm(formid){
	formid = $(formid);
	//Insertion.After(formid,'<div id="cover"></div>') // create dive to hold responce.
	var formsize = Element.getDimensions(formid)
	//alert(formsize.height)
	var pars = Form.serialize(formid)
	var url = formid.action
	
	
	//alert("2action is "+formid.action)
	var myAjax = new Ajax.Updater(
			'cover', 
			url, 
			{
				method: 'post', 
				parameters: pars
			});
		
	Position.clone($('cover'), formid)	
	$('cover').style.height=formsize.height+"px"
	formid.style.display="none"
	$('cover').style.display="block"
	return false
}



function checkRequiered(formtocheck){
	var readytosend = "true";
	var CCerror ="";

	fields = Form.getElements(formtocheck);
	fields.each(function(node){							
			if(Element.hasClassName(node, "required")){
					//alert("checking Field:  "+ node.nodeName + ': ' + node.id);
				// Save values in Cookie if not a CC number;
				if (!Element.hasClassName(node, "ccardnumber")){
					if ($F(node) != ""){
						Set_Cookie($(node).id, $F(node), "", "/");
					}
					//alert("setting c for "+node.id);
				}
					
				if(Element.hasClassName(node, "email")){
					//alert("Validate email address");
					// Validate email address;
					if($F(node)=="" || !isValidEmail($F(node))){
						highlightRequiered(node, "required")
						readytosend = "false"
					}
				}else if (Element.hasClassName(node, "ccardnumber")){
					//alert("Validate Visa Number");
					// Validate Visa Number 
					var cardtype = document.getElementsByClassName('cardtype');
					if(!validateCreditCardNumber($F(node),$F(cardtype[0]))){
						CCerror = "Credit Card appears to be invalid \n Please verify the number and card type are correct.";
						highlightRequiered(node, "required")
						readytosend = "false"
					}
					//alert("Validate "+ $F(cardtype[0])+ ' : '+ node.nodeName + ': ' + node.id);
				}else if (Element.hasClassName(node, "agree")){
					// Must Agree 
					if($F(node)!="yes"){
						CCerror += "You must agree to the Rules and Regulations ";
						//highlightRequiered(node, "required")
						readytosend = "false"
					}
					//alert("Must Agree "+$F(node));
				}else{
					// Higlight empty fields
					if($F(node)==""){
						highlightRequiered(node, "required")
						readytosend = "false"
					}
					//alert("check for empty "+ node.nodeName + ': ' + node.id);
				}
			}
		})
		
	//alert(readytosend);
		
	if(readytosend=="true"){
		//alert("OK all looks good");
		if($(formtocheck).hasClassName('ajax')){
	   		 AjaxForm(formtocheck);
			 return false;
		}else{
			return true;
		}

	}else{
		alert("Please verify that all required fields are completed \nRequired fields have been highlighted in yellow \n\n"+CCerror);
		return false;

	}

}


isValidEmail = function(val){
    var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    if (!val.match(re)) {
        return false;
    } else {
        return true;
    }
}


isValidCC = function(cardNumber, cardType)
{
  var isValid = false;
  var ccCheckRegExp = /[^\d ]/;
  isValid = !ccCheckRegExp.test(cardNumber);

  if (isValid)
  {
    var cardNumbersOnly = cardNumber.replace(/ /g,"");
    var cardNumberLength = cardNumbersOnly.length;
    var lengthIsValid = false;
    var prefixIsValid = false;
    var prefixRegExp;

    switch(cardType)
    {
      case "mastercard":
        lengthIsValid = (cardNumberLength == 16);
        prefixRegExp = /^5[1-5]/;
        break;

      case "visa":
        lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
        prefixRegExp = /^4/;
        break;

      case "amex":
        lengthIsValid = (cardNumberLength == 15);
        prefixRegExp = /^3(4|7)/;
        break;

      default:
        prefixRegExp = /^$/;
        alert("Card type not found: "+cardType);
    }

    prefixIsValid = prefixRegExp.test(cardNumbersOnly);
    isValid = prefixIsValid && lengthIsValid;
  }

  if (isValid)
  {
    var numberProduct;
    var numberProductDigitIndex;
    var checkSumTotal = 0;

    for (digitCounter = cardNumberLength - 1; 
      digitCounter >= 0; 
      digitCounter--)
    {
      checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
      digitCounter--;
      numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
      for (var productDigitCounter = 0;
        productDigitCounter < numberProduct.length; 
        productDigitCounter++)
      {
        checkSumTotal += 
          parseInt(numberProduct.charAt(productDigitCounter));
      }
    }

    isValid = (checkSumTotal % 10 == 0);
  }

  return isValid;
}


function SelectValueSet(SelectName, Value){
	SelectObject = $(SelectName);
	for(index = 0; index < SelectObject.length; index++){
		if(SelectObject[index].value == Value){
			SelectObject.selectedIndex = index;
		}
	}
}


function highlightRequiered(id, message){
	$(id).style.color = "black"
	$(id).value = message
	new Effect.Highlight(id,{afterFinish: function(){$(id).value="";$(id).style.color = "";$(id).style.background = "#EFF4AE";}})
}


function highlightinvalid(id, message){
	$(id).style.color = "black"
	var v = $(id).value
	$(id).value = message
	new Effect.Highlight(id,{afterFinish: function(){$(id).value=v;$(id).style.color = "";$(id).style.background = "#EFF4AE";}})
}


// Slideshow effect


var SlideShow = Class.create();
SlideShow.prototype = {
   // using css, set imgNodeTop and imgNodeBottom to the same position using top and left
   // then set imgNodeTop's z-index to be higher
   // also pass in an array of the sources
   initialize: function(imgNode, imgCase, imageSources, options) {
       // internally store the given values
       this.imgTop = $(imgNode);
       this.imgBottom = $(imgCase);
       this.sources = imageSources;
       this.options = Object.extend({
           fadeDuration: 1,
           showDuration: 8
           }, options);
                 // set the top image source to the first source
       this.imgTop.src = this.sources[0];
       this.position = 0;
       this.onTop = 1;
   this.started = false;
   this.sources.each(this.prefetch);
   },
 prefetch: function(source) {
   var img = document.createElement('img');
   img.src = source;
 },
   start: function() {
       window.setTimeout(this.next.bind(this), this.options.showDuration*1000);
   this.started = true;
   },
 stop: function() {
   this.started = false;
 },
   next: function() {
       // set the bottom image to the next source
   var pos = this.position==this.sources.length-1 ? 0 : this.position+1;
		this.imgBottom.style.background = "url("+this.sources[pos]+")"
       // fade away the top image to slowly reveal the bottom image
       new Effect.Fade(this.imgTop, {
           duration: this.options.fadeDuration,
           afterFinish: function() {
               // when finished, set the top image to the last image (hopefully it won't flicker)
               this.imgTop.src = this.sources[this.position];
               this.imgTop.show();
               // start over
               if (this.started) this.start();
           }.bind(this)
       });
   // increment the position, wrapping if needed
   this.position++;
   if (this.position==this.sources.length) this.position = 0;
   }
};

//var headers = ['/media/images/headers/header2.jpg','/media/images/headers/header3.jpg','/media/images/headers/header4.jpg','/media/images/headers/header1.jpg'];

 
Event.onReady(function() {	
	if(headers.length >1){
		ss1 = new SlideShow("himg", "header", headers,{ fadeDuration: 2, showDuration: 3 } );
		ss1.start();
	}
});

function opengallery(id){
	gallerylightWindow = new lightwindow({hideGalleryTab:true});
	var url = "/modules/Gallery/WCMS_SlideShow.php?id="+id
	gallerylightWindow.activateWindow(
		{href: url, 
		height: 640, 
		width: 760,
		scrolling:false});
}
