var BASE_URI = "/";


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 popGallery(id)
{
	var url = '/demo/gallery.php?id=' + id;
	window = window.open(url, '', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=650,height=875,left = 200,top = 50.5');
}

function addWithQuantity(id)
{
	var tmp = 'qty_' + id;
	var quantity = eval("document.purchaseForm." + tmp + ".value");
	var loc = BASE_URI+'addcart.php?id=' + id + '&quantity=' + quantity;
	document.location=loc;
}

function addWithQuantityWholesale(id)
{
	var tmp = 'qty_' + id;
	var quantity = eval("document.purchaseForm." + tmp + ".value");
	if(quantity < 3) {
		alert('You must purchase at least 3 of an item!');
		return false;
	}
	var loc = 'addcart.php?id=' + id + '&quantity=' + quantity + '&wholesale=1';
	document.location=loc;
}

function copyShipping()
{
	document.forms.addressForm.b_firstname.value=document.forms.addressForm.s_firstname.value;
	document.forms.addressForm.b_lastname.value=document.forms.addressForm.s_lastname.value;
	document.forms.addressForm.b_business_name.value=document.forms.addressForm.s_business_name.value;
	document.forms.addressForm.b_address.value=document.forms.addressForm.s_address.value;
	document.forms.addressForm.b_city.value=document.forms.addressForm.s_city.value;
	document.forms.addressForm.b_state.value=document.forms.addressForm.s_state.value;
	document.forms.addressForm.b_zip.value=document.forms.addressForm.s_zip.value;
	document.forms.addressForm.b_phone.value=document.forms.addressForm.s_phone.value;
	document.forms.addressForm.b_email.value=document.forms.addressForm.s_email.value;
	return;
}

function submitTheForm(stype)
{
	// stype is the submit type (Billing, Contact, etc)
	if(!stype) var stype="";
	
	// Is stype Billing? If so, require Shipping Info
	if(stype=="Billing") {
	  if (document.forms.addressForm.s_firstname.value == '') {
	  	alert('Shipping Firstname is required');
	  	return false;
	  }
	  if (document.forms.addressForm.s_lastname.value == '') {
	  	alert('Shipping Lastname is required');
	  	return false;
	  }
	  if (document.forms.addressForm.s_address.value == '') {
	  	alert('Shipping Address is required');
	  	return false;
	  }
	  if (document.forms.addressForm.s_city.value == '') {
	  	alert('Shipping City is required');
	  	return false;
	  }
	  if (document.forms.addressForm.s_state.value == '') {
	  	alert('Shipping State is required');
	  	return false;
	  }
	  if (document.forms.addressForm.s_zip.value == '') {
	  	alert('Shipping Zip is required');
	  	return false;
	  }
	  if (document.forms.addressForm.s_country.value == '') {
	  	alert('Shipping Country is required');
	  	return false;
	  }
	  if (document.forms.addressForm.s_email.value == '') {
	  	alert('Shipping Email is required');
	  	return false;
	  }
	  // End required fields for Billing
	}
	
	if (document.forms.addressForm.b_firstname.value == '') {
		alert(stype+' Firstname is required');
		return false;
	}
	if (document.forms.addressForm.b_lastname.value == '') {
		alert(stype+' Lastname is required');
		return false;
	}
	if (document.forms.addressForm.b_address.value == '') {
		alert(stype+' Address is required');
		return false;
	}
	if (document.forms.addressForm.b_city.value == '') {
		alert(stype+' City is required');
		return false;
	}
	if (document.forms.addressForm.b_state.value == '') {
		alert(stype+' State is required');
		return false;
	}
	if (document.forms.addressForm.b_zip.value == '') {
		alert(stype+' Zip is required');
		return false;
	}
	 if (document.forms.addressForm.b_email.value == '') {
	  	alert(stype +' Email is required');
	  	return false;
	  }	
	if (document.forms.addressForm.whereheard.value == '') {
		alert('How you heard is required');
		return false;
	}	
	
	document.forms['addressForm'].submit();
	return;
}

//BEGIN CREDIT CARD SCRIPTS
var ccErrorNo = 0;
var ccErrors = new Array ()

ccErrors [0] = "Unknown card type";
ccErrors [1] = "No card number provided";
ccErrors [2] = "Credit card number is in invalid format";
ccErrors [3] = "Credit card number is invalid";
ccErrors [4] = "Credit card number has an inappropriate number of digits";

function trim(val) { 
    var ret = val.replace(/^\s+/, ''); 
    ret = ret.replace(/\s+$/, ''); 
  
    return ret; 
} 

function testCreditCard () {
  myCardNo = document.getElementById('cc').value;
  myCardType = document.getElementById('typeofcard').value;
  myCardName = trim(document.getElementById('nameoncard').value);
  myCardMth = parseInt('0'+document.getElementById('expmm').value,10);
  myCardYear = parseInt('20'+document.getElementById('expyy').value,10);
  
  //alert(myCardMth);
  //return false;
  
  var currentTime = new Date();
  var month = currentTime.getMonth() + 1;
  var year = currentTime.getFullYear();
  
  if(myCardName.length == 0) {
  	 alert('Name on Card is required.');
  	 return false;
  }
  
  if(myCardYear < year) {
  	alert('Invalid Expiry Year');
  	return false;
  }

  if(myCardMth < 1) {
  	alert('Invalid Expiry Month <1');
 	return false;
 }

  if(myCardMth > 12) {
 	alert('Invalid Expiry Month >12');
  	return false;
 }

  if(myCardYear == year) {
  	if(myCardMth < month) {
  	alert('Invalid Expiry Month or Year');
  	return false;
  }
  }
  
  if (checkCreditCard (myCardNo,myCardType)) {
    return true;
  } 
  else {
  	alert (ccErrors[ccErrorNo]);
  	return false;
  }
}


function checkCreditCard (cardnumber, cardname) {
     
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types.
  
  //  Name:      As in the selection box of the form - must be same as user's
  //  Length:    List of possible valid lengths of the card number for the card
  //  prefixes:  List of possible prefixes for the card
  //  checkdigit Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,16", 
               prefixes: "300,301,302,303,304,305,36,38,55",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305,36,38",
               checkdigit: true};
  cards [4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011,650",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "15,16", 
               prefixes: "3,1800,2131",
               checkdigit: true};
  cards [7] = {name: "enRoute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
  cards [8] = {name: "Solo", 
               length: "16,18,19", 
               prefixes: "6334, 6767",
               checkdigit: true};
  cards [9] = {name: "Switch", 
               length: "16,18,19", 
               prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
               checkdigit: true};
  cards [10] = {name: "Maestro", 
               length: "16,18", 
               prefixes: "5020,6",
               checkdigit: true};
  cards [11] = {name: "VisaElectron", 
               length: "16", 
               prefixes: "417500,4917,4913",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardnumber = cardnumber.replace (/\s/g, "");
  
  // Check that the number is numeric
  var cardNo = cardnumber
  var cardexp = /^[0-9]{13,19}$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the 
  // length if all else was hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return false; 
  };   
  
  // The credit card is in the required format.
  return true;
}

/*============================================================================*/
//END CREDIT CARD CHECKS


function onlyNumbers(e)
{

if ([e.keyCode||e.which]==8 || [e.keyCode||e.which]==46 ) //this is to allow backspace and period
return true;
if ([e.keyCode||e.which] < 48 || [e.keyCode||e.which] > 57)
e.preventDefault? e.preventDefault() : e.returnValue = false;
}

/**** Lightbox functions ****/
function openLightbox(m,w,h,c) {
	
	// Make sure dimension aren't larger than the window
	if(w > window.innerWidth) w = window.innerWidth - 40;
	if(h > window.innerHeight) h = window.innerHeight - 40;
	
	var top = ((($(window).height()/2)-(h/2))); if(top < 0) top = 10;
	var left = ((($(window).width()/2)-(w/2))); if(left < 0) left = 10;
	
	
	
	if(typeof(c) == "undefined") c = 1;
	$("#lightbox-frame").css("width",w+"px").css("height",h+"px").css("left",left+"px").css("top",top+"px");		
	$("#lightbox-content").css("width",(w)+"px").css("height",(h)+"px");	
	$("#lightbox-content").html((c ? "<a href=\"#\" onclick=\"closeLightbox();return false;\" id=\"lightbox-close\"></a>" : "")+m);
	$("#lightbox-bg").show();
	$("#lightbox").show();
	$("#lightbox-content").scrollTop(0);
		
	// Move the close button if the scroll bar appears
	if(document.getElementById("lightbox-content").scrollHeight > $("#lightbox-content").height()) $("#lightbox-close").css("right","20px");
	else $("#lightbox-close").css("right","10px");	
	
	// Check again for the scroll bar after all the images have loaded
	
};

function closeLightbox() {
	$("#lightbox").hide();
	$("#lightbox-bg").hide();
};
/**** ****/

function goingBack() {
	$("#lightbox-back").css("background-image","url(/img/back-button-anim.gif)");
}

function goingFwd() {
	$("#lightbox-back").show();
	$("#lightbox-back").css("background-image","url(/img/back-button-anim.gif)");
	$("#lightbox-back").css({"-moz-transform":"scaleX(-1)","-webkit-transform":"scaleX(-1)","-o-transform":"scaleX(-1)","transform":"scaleX(-1)","filter":"fliph"});
}

function loadTeacher(teacher) {
	$.ajax({url:BASE_URI+"teacher/teacher.php?tchTeacher="+teacher,type:"GET",dataType:"html",success:function(html){openLightbox(html,700,500)}});		
}

function loadTeachersQuilt(quilt_image, quilt_name, teacher) {
	$.ajax({url:BASE_URI+"teacher/show_quilt.php?tchImage="+quilt_image+"&tchPixName="+quilt_name+"&teacher="+teacher,type:"GET",dataType:"html",success:function(html){openLightbox(html,700,500)}});			
}

function loadTeachingSchedule(teacher) { 
	$.ajax({url:BASE_URI+"teacher/show_teaching_calendar.php?teacher="+teacher,type:"GET",dataType:"html",success:function(html){openLightbox(html)}});		
}

function loadScheduleInfo(sid) {
	$.ajax({url:BASE_URI+"teacher/popup_event.php?id="+sid,type:"GET",dataType:"html",success:function(html){openLightbox(html)}});		
}

function loadScheduleInstructions(did, sid, stype) {
	$.ajax({url:BASE_URI+"teacher/popup_instruction.php?instID="+did+"&sid="+sid+"&stype="+stype,type:"GET",dataType:"html",success:function(html){openLightbox(html)}});		
}



function loadShop(shop) {
	$.ajax({url:BASE_URI+"certifiedshops/shop/shop.php?tchShop="+shop,type:"GET",dataType:"html",success:function(html){openLightbox(html,700,500,1)}});		
}

function loadShopEvents(shop) {
	$.ajax({url:BASE_URI+"certifiedshops/event/show_event_calendar.php?shop="+shop,type:"GET",dataType:"html",success:function(html){openLightbox(html,700,500)}});		
}

function loadShopEventInfo(eid) {
	$.ajax({url:BASE_URI+"certifiedshops/event/popup_event.php?id="+eid,type:"GET",dataType:"html",success:function(html){openLightbox(html,700,500)}});		
}

function loadShopsQuilt(quilt_image, quilt_name, shop) {
	$.ajax({url:BASE_URI+"certifiedshops/shop/show_quilt.php?tchImage="+quilt_image+"&tchPixName="+quilt_name+"&shop="+shop,type:"GET",dataType:"html",success:function(html){openLightbox(html,700,500)}});			
}

function loadTicket() {
	$.ajax({url:BASE_URI+"system/inc/ticket/post.php",type:"GET",dataType:"html",success:function(html){openLightbox(html,550,450)}});		
}
