var idSlideShowTimeout;
var SlideShowInterval = 4000;
var SlideShow = false; 
var uds_req;
var UDS_SignUp = false;

function GetPicLabel (PicId) {
	return (top.window.order_entry_frame.document.getElementById("row"+PicId+"_label").innerHTML);
}

function buildPosterPhotoList (photoList) {
var illegalChars = /\W\s/g;
 	 // allow only letters, numbers, newline, and underscores
	if (illegalChars.test(photoList)) {
       		alert("Warning: One or more photo id(s) might be wrong...please double-check");
       		photoList = photoList.replace(illegalChars, "");
    	}
	return (photoList);
}

function buildPosterInfo (posterIndex) {
var noDesignPicked = true;

var posterInfoStr = GetPicLabel(posterIndex)+"::";
		if (ArrayCart[posterIndex].p_name) {
			posterInfoStr += "\nDesign:"+ArrayCart[posterIndex].p_name;
			noDesignPicked = false;
		} 
		 if (ArrayCart[posterIndex].p_first_name) {
			posterInfoStr += "\nFirstName:"+ArrayCart[posterIndex].p_first_name;
			noDesignPicked = false;
		}
		if (ArrayCart[posterIndex].p_last_name) {
			posterInfoStr += "\nLastName:"+ArrayCart[posterIndex].p_last_name;
			noDesignPicked = false;			
		}
		if (ArrayCart[posterIndex].p_jersey_num) {
			posterInfoStr += "\nJersey#:"+ArrayCart[posterIndex].p_jersey_num;
			noDesignPicked = false;			
		}
		if (ArrayCart[posterIndex].p_team_name) {
			posterInfoStr += "\nTeamName:"+ArrayCart[posterIndex].p_team_name;
			noDesignPicked = false;			
		}
		if (ArrayCart[posterIndex].p_photos) {
			posterInfoStr += "\nAdditionalPhotos:\n"+buildPosterPhotoList(ArrayCart[posterIndex].p_photos);
			noDesignPicked = false;			
		}
		if (noDesignPicked) {
			posterInfoStr += "NO DESIGN PICKED";
		}
		return (posterInfoStr);
}

function getUDSgameList() {//called by the "USE CODE" button
var UDS_code = (parent.document.getElementById("tUDC").value).replace(/[^a-zA-Z0-9]+/g,'');
	if (UDS_code.length==0 ) {
		alert("Invalid Download Code...\r\nPlease re-enter code");
	} else {
		url = "/Scripts/xml-dispatch.php?mode=getUDSgames&UDS_code="+UDS_code;
		xml_to_server(url);
	}
} 

function UDS_open () {//called by the check button of the delivery estimate layer button
		if (I13x19 > 0) {
				for (var i=1; i<= I13x19; i++) {
						if  (Arry13x19[i].PosterInfoStr.indexOf("NO DESIGN PICKED") != -1) {
								if (!confirm('You have not picked a Poster Design!\n\nClick "OK" if this is what you want\nClick "CANCEL" to go back and pick a design') ) { 
										return false;
								}
	 					}
				}
		}			
		
		//grayOut(true, {'layerId':'UDS_layer'});
			
		if ( (IDGTL>0) || (I13x19>0) || (IUDS>0) ) {//only open if there is a DGTL or poster purchase.
		 		parent.document.getElementById("UDS_layer").style.visibility="visible";
		 		parent.document.getElementById("UDS_layer").style.display="block";
	 	} else {
	 			UDS_SignUp = false;
	 			PayPalCart();
		}			
}

function validate_UDS_downloads(UDC_code) {
var gamesList = UDS_GamesList.split(":");
var tournament_id = "";
var validGames = "";
var downloadList = "";
var mixture = false;
var found = false;

		//get a list of UDS valid games
		for (var i=0; i<gamesList.length-1; i++) {
				tournament_id = gamesList[i].split("_")[0];	
				validGames+= gamesList[i].split("_")[1]+" ";;	
		}
		for (var i=0; i<currCartRow; i++) {
			if (ArrayCart[i].sDGTL  > 0)  {
				photo_id 		= ArrayCart[i].title;
				photo_t_id 	= photo_id.split("_")[0];
				photo_g_id 	= photo_id.split("_")[1];
				if ( (photo_t_id==tournament_id) && (validGames.indexOf(photo_g_id)!=-1) ) {
					downloadList += photo_id+":";
					//ArrayCart[i].sDGTL = 0;			//remove it from the cart
					ArrayCart[i].UDS = 0;			//mark it as a UDS item
					found = true;
				} else {
					mixture = true;
				}
			}
		}
		if (mixture && found)  {
			alert("Warning: Some of the photos you selected\r\nare not covered by the unlimited\r\ndownload code you entered.");
		} else if (mixture && (!found)) {
			alert("Invalid Code");
			return false;
		}		
		
		sumPhotos(tournament_id, validGames);
		
		//grayOut(false);
	 	parent.document.getElementById("UDS_layer").style.visibility="hidden";
	 	parent.document.getElementById("UDS_layer").style.display="block";
	 	
	 	UDS_SignUp = true;		
	 	
		//MsgShow('UDS_downloading_layer');
	 	//var url = '/Scripts/uds_downloadPhotos.php?pl='+downloadList+"&UDC="+UDC_code;
	 	//document.getElementById('UDS_download_link').href = url;
	 	//window.open(url);
	 	
	 	var d = new Date();
		var elapsedSecs = d.getTime();
	 	var hash_str = downloadList+"||"+UDC_code+"||"+elapsedSecs;
	 	var url = "/Scripts/xml-dispatch.php?mode=getDownloadKey&photoList="+hash_str;
		xml_to_server(url);	 	
	 	return true;
}

function PDF_process_selections(gameList) {
var tmp1 = gameList.split(":");	
var tmp = (tmp1[0]).split("_");

var tournament_id = tmp[0];
var game_id = tmp[1];
var team_id = tmp[2];
var txn_id  = tmp[3];
var mask = tournament_id+"_"+game_id;
var photo_list = "";
var teamPhoto_mask = "88";

	MsgHide ("UDS_layer");
	
	//make sure 3 and only three photos selected
	if (currCartRow != 3) {
		alert ("Please select only three items\r\n\r\nThank You.");
		return false;
	}
	
	//get list of photos ids
	for (var i=0; i<3; i++) {
		var photo_id = GetPicLabel(i);

		//make sure we are picking photos from the correct team photos
		if (photo_id.indexOf(mask) != 0) {
			alert(photo_id+" is not from photos of your team");
			return false;
		}
	
		//make sure there is no team photo in the list
	    if (  ((photo_id.split("_"))[3]).indexOf(teamPhoto_mask) != -1) {
	    	alert("Please remove the team photo from the cart");
	    	return false;
	    }
		photo_list += photo_id+":";
	}
	
	//update sale database with selection and zero cost
	var url = "/Scripts/xml-dispatch.php?mode=PDF_updateDB&txn_id="+txn_id+"&tournament_id="+tournament_id+"&team_id="+team_id+"&event=PictureDay&photo_list="+photo_list;
	xml_to_server(url);
}

function UDS_validate_code (gameListType) {//called by xml-dispatch return
var downloadCode = (parent.document.getElementById("tUDC").value).replace(/[^a-zA-Z0-9]+/g,'');
var nonUDS_digital = 0;

var tmp = gameListType.split("::");	
var packageType = tmp[0];
var gameList = tmp[1]; 

		//get list of games associated with download_code
	 	if (!gameList) {
 			alert('Invalid Code');
 			UDS_SignUp = false;
 			return false;
	 	} 
	 	
	 	//is this a Picture Day Family Package?
		if (packageType == "PDF") {
			if (confirm ("You have entered a Family Package Code.\n\r\r\nPlease make sure you have selected ONLY 3 JPG photos.\r\nThese photos (and team photo) will represent the photos you want printed and mailed to you.\r\n\r\nClick OK to proceed.")) {
				PDF_process_selections(gameList);
			} else {
				MsgHide ("UDS_layer");
			}
			return;
		}	 	
	 	
	 	UDS_GamesList = gameList;
	 	
	 	//validate selected DGTL photos
	 	if (!validate_UDS_downloads(downloadCode)) {
	 		return false;
 		}
	 	//parent.document.getElementById("UDS_layer").style.visibility="hidden";
	 	//parent.document.getElementById("UDS_layer").style.display="block";
	 	//UDS_SignUp = true;
	 	
	 	
		if (IDGTL+I4x6+I5x7+I8x10+I13x19 == 0) {
				return false;
		} else {
	 			PayPalCart();
 		}
}
function UDS_lateSignUp_confirm () {
	for (var i=1; i<=IDGTL; i++) {
			tournament_id = ArryDGTL[i].PicId.split("_")[0];
			if (tournament_id.indexOf("9") == 0)  {//Picture Day photos:No team or Family package. Remove the digital photos.
				alert("Please remove the Picture Day digital photo(s) from your cart. You did not sign up for either the Team or Family package.");
				MsgHide('UDS_layer');
				return false;
			}	
	}

 	MsgHide('UDS_layer');
 	MsgShow('UDS_lateSignUp_layer');
}

function UDS_close () { //called by the "I DO NOT HAVE A CODE" button
	 	//parent.document.getElementById("UDS_layer").style.visibility="hidden";
	 	//parent.document.getElementById("UDS_layer").style.display="block";
	 	
	 	MsgHide('UDS_layer');
/*	 	if (confirm("Do you want to see if your team can still sign up\r\nfor the Unlimited Download Offer?\r\n\r\n")) {
	 		var url  = "http://ArizonaActionPhotos.com/promos/prePay_deal/prePay.php?tournament_id="+curr_tournament_id;
			window.open(url, 'UnlimitedDownloadOffer', 'toolbar=no, directories=no, location=no, statusbar=no, menubar=no, resizable=yes, scrollbars=yes');
	 	} else {
*/		 	UDS_SignUp = false;
		 	PayPalCart();
// 	}
}

function PayPalCart() {
var sandBox   = 1;
var itemNo = 1;
	initializeCart(currCartRow);
	document.writeln ('<body>');

	if (sandBox == 0) {
		document.writeln ('<form id="PayPal_entry_form" name="PayPal_entry_form" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="POST">');
		document.writeln ('<input type="hidden" name="business" value="raphaelsoetan@arizonaactionphotos.net">');
	} else {
		document.writeln ('<form name="PayPal_entry_form" id="PayPal_entry_form" action="https://www.paypal.com/cgi-bin/webscr" method="POST">');
		document.writeln ('<input type="hidden" name="business" value="raphaelsoetan@cox.net">');
	}
	document.writeln ('<input type="hidden" name="cmd" value="_cart">');
	document.writeln ('<input type="hidden" name="upload" value="1">');
	document.writeln ('<input type="hidden" name="custom" value="PSC_'+curr_tournament_id+'_'+curr_team_id+'">'); //can also be unlimited download signup transaction.

	if (IDGTL > 0) {
		for (var i=1; i<= IDGTL; i++) {
			IDGTLDiscount = formatCurrency(ArryDGTL[i].ebd)+"/"+formatCurrency(ArryDGTL[i].vd);
			document.writeln ('<input type="hidden" name="item_name_'+itemNo+'" value="DGTL">');
			document.writeln ('<input type="hidden" name="quantity_'+itemNo+'" value="'+ArryDGTL[i].PicQty+'">');
			document.writeln ('<input type="hidden" name="on0_'+itemNo+'" value="\nPhoto ID">');
			document.writeln ('<input type="hidden" name="os0_'+itemNo+'" value="'+ArryDGTL[i].PicId+'">');
			document.writeln ('<input type="hidden" name="on1_'+itemNo+'" value="Unit Discount (EarlyBird/Volume)">');
			document.writeln ('<input type="hidden" name="os1_'+itemNo+'" value="'+IDGTLDiscount+'">');
			document.writeln ('<input type="hidden" name="amount_'+itemNo+'" value="'+ArryDGTL[i].cost+'">');
			++itemNo;
		}
	}
	if (I4x6 > 0) {
		for (var i=1; i<= I4x6; i++) {
			I4x6Discount = formatCurrency(Arry4x6[i].ebd)+"/"+formatCurrency(Arry4x6[i].vd);
			document.writeln ('<input type="hidden" name="item_name_'+itemNo+'" value="Print_4x6">');
			document.writeln ('<input type="hidden" name="quantity_'+itemNo+'" value="'+Arry4x6[i].PicQty+'">');
			document.writeln ('<input type="hidden" name="on0_'+itemNo+'" value="\nPhoto ID">');
			document.writeln ('<input type="hidden" name="os0_'+itemNo+'" value="'+Arry4x6[i].PicId+'">');
			document.writeln ('<input type="hidden" name="on1_'+itemNo+'" value="Unit Discount (EarlyBird/Volume)">');
			document.writeln ('<input type="hidden" name="os1_'+itemNo+'" value="'+I4x6Discount+'">');
			document.writeln ('<input type="hidden" name="amount_'+itemNo+'" value="'+Arry4x6[i].cost+'">');
			++itemNo;
		}
	}

	if (I5x7> 0) {
		for (var i=1; i<= I5x7; i++) {
			I5x7Discount = formatCurrency(Arry5x7[i].ebd)+"/"+formatCurrency(Arry5x7[i].vd);
			document.writeln ('<input type="hidden" name="item_name_'+itemNo+'" value="Print_5x7">');
			document.writeln ('<input type="hidden" name="quantity_'+itemNo+'" value="'+Arry5x7[i].PicQty+'">');
			document.writeln ('<input type="hidden" name="on0_'+itemNo+'" value="\nPhoto ID">');
			document.writeln ('<input type="hidden" name="os0_'+itemNo+'" value="'+Arry5x7[i].PicId+'">');
			document.writeln ('<input type="hidden" name="on1_'+itemNo+'" value="Unit Discount (EarlyBird/Volume)">');
			document.writeln ('<input type="hidden" name="os1_'+itemNo+'" value="'+I5x7Discount+'">');
			document.writeln ('<input type="hidden" name="amount_'+itemNo+'" value="'+Arry5x7[i].cost+'">');
			++itemNo;
		}
	}

	if (I8x10 > 0) {
		for (var i=1; i<= I8x10; i++) {
			I8x10Discount = formatCurrency(Arry8x10[i].ebd)+"/"+formatCurrency(Arry8x10[i].vd);
			document.writeln ('<input type="hidden" name="item_name_'+itemNo+'" value="Print_8x10">');
			document.writeln ('<input type="hidden" name="quantity_'+itemNo+'" value="'+Arry8x10[i].PicQty+'">');
			document.writeln ('<input type="hidden" name="on0_'+itemNo+'" value="\nPhoto ID">');
			document.writeln ('<input type="hidden" name="os0_'+itemNo+'" value="'+Arry8x10[i].PicId+'">');
			document.writeln ('<input type="hidden" name="on1_'+itemNo+'" value="Unit Discount (EarlyBird/Volume)">');
			document.writeln ('<input type="hidden" name="os1_'+itemNo+'" value="'+I8x10Discount+'">');
			document.writeln ('<input type="hidden" name="amount_'+itemNo+'" value="'+Arry8x10[i].cost+'">');
			++itemNo;
		}
	}

	if (I13x19 > 0) {
		for (var i=1; i<= I13x19; i++) {
			I13x19Discount = formatCurrency(Arry13x19[i].ebd)+"/"+formatCurrency(Arry13x19[i].vd);
			document.writeln ('<input type="hidden" name="item_name_'+itemNo+'" value="Poster">');
			document.writeln ('<input type="hidden" name="quantity_'+itemNo+'" value="'+Arry13x19[i].PicQty+'">');
			document.writeln ('<input type="hidden" name="on0_'+itemNo+'" value="\nPhoto ID">');
			document.writeln ('<input type="hidden" name="os0_'+itemNo+'" value="'+Arry13x19[i].PosterInfoStr+'">');
			document.writeln ('<input type="hidden" name="on1_'+itemNo+'" value="Unit Discount (EarlyBird/Volume)">');
			document.writeln ('<input type="hidden" name="os1_'+itemNo+'" value="'+I13x19Discount+'">');
			document.writeln ('<input type="hidden" name="amount_'+itemNo+'" value="'+Arry13x19[i].cost+'">');
			++itemNo;
		}
	}

	document.writeln ('<input type="hidden" name="shipping_1" value="'+shipping+'">');
	document.writeln ('<input type="hidden" name="handling_1" value="'+handling+'">');
	document.writeln ('</form>');
	document.writeln ('</body>');
 	
 	document.getElementById("PayPal_entry_form").submit();
	
//	if (IDGTL > 0) {
//		alert ("You will get a download email WITHIN A MINUTE of making your payment.\n\r\n\rIf YOU DO NOT get the email,\r\nplease check your junk email folder.\r\r\n\nTHANK YOU!");
//	}
}

function SaveRowData (rowIndex, colIndex, CB_event) {
parent.ArrayCart[rowIndex].UDS=1;
var a=parent.ArrayCart[rowIndex];
var row_id="row"+rowIndex;
var poster_id = row_id+"_06";

var s13x19 = top.window.order_entry_frame.document.getElementById("order_entry_form")[row_id+"_04"].value;
var DGTL    = top.window.order_entry_frame.document.getElementById(row_id+"_05");
var photo_id = GetPicLabel(rowIndex);
var photo_index = photo_id.split("_")[3];//to be used to detect enhanced team photos - 888 or 889.

	if   ( (DGTL.checked) && (s13x19>0) ) 	{//poster and DGTL both selected
		alert ('By selecting a poster, you automatically get the\r\ncorresponding JPG, and do not need to select the JPG option.\r\n\r\nFor further information on posters, please see the\r\n"Poster Designs" link at the bottom of the page.')
		DGTL.checked = false;
		CB_event=false;
	}


	if (CB_event = "true")	{ //check box was clicked
		if (document.getElementById(row_id+"_05").checked) {
			a.sDGTL = 1;
		}
		else {
			a.sDGTL = 0;
		}
	}

    var entry = top.window.order_entry_frame.document.getElementById("order_entry_form")[row_id+"_"+colIndex].value;

	if ( isNaN(entry) || (entry<0) || isNaN(parseInt(entry)) )  {
		alert("Please enter a positive numeric value (0-99)");
		parent.ShowCartRowValues (row_id, rowIndex);
		return false;
	}

	if ( (photo_index.indexOf("88") == 0) && colIndex!="03" && (colIndex!="04" && entry!=0 || DGTL.checked) )  {//if enhanced team photo and not 8x10 or Poster size
		alert("Enhanced Team Photos are only available in 8x10 and Poster sizes.");
		if (DGTL.checked) {
			DGTL.checked = false;
			a.sDGTL = 0;
		}
		parent.ShowCartRowValues (row_id, rowIndex);
		return false;
	}

	if ( (parent.curr_tournament_id.indexOf("9") == 0) && colIndex=="01" && entry!=0)  {//if enhanced team photo and not 8x10 or Poster size
		alert("Picture Day photos are only available in 5x7 and larger sizes.");
		parent.ShowCartRowValues (row_id, rowIndex);
		return false;
	}

	if ( (parent.curr_tournament_id.indexOf("9") == 0) && (DGTL.checked) && (!parent.PD_message) )  {//if enhanced team photo and not 8x10 or Poster size
		parent.PD_message = true;
		alert("Did you sign up for the TEAM or FAMILY package?\n\r\n\rIf you did not, all selected digital photos will be removed from your cart during checkout.");
	}

	a.s4x6=top.window.order_entry_frame.document.getElementById("order_entry_form")[row_id+"_01"].value;
	a.s5x7=top.window.order_entry_frame.document.getElementById("order_entry_form")[row_id+"_02"].value;
	a.s8x10=top.window.order_entry_frame.document.getElementById("order_entry_form")[row_id+"_03"].value;
	a.s13x19=top.window.order_entry_frame.document.getElementById("order_entry_form")[row_id+"_04"].value;
	poster_btn_status = parent.ArrayCart[rowIndex].p_status;

	if (a.s13x19>0) {
		if (poster_btn_status == 0) {
			document.getElementById(poster_id).src = "images/poster_form_green_button.gif"
		} else {
			document.getElementById(poster_id).src = "images/poster_form_yellow_button.gif"
		}
	} else {
		document.getElementById(poster_id).src = "images/poster_form_red_button.gif";
	}

	parent.sumPhotos();
}

function showCartImg(index) {
 var imgMain = parent.document.getElementById("fpGalleryMainImg_2337");
 var c = parent.ArrayCart[index];
 	currentImgIndex = c.id;

	imgMain.src = c.src;
	//imgMain.title = c.title;
	imgMain.alt = c.title;

	if (c.ht==100) {
		{imgMain.style.width = 320;imgMain.style.height = 480}
	} else {
		{imgMain.style.width = 480;imgMain.style.height = 320}
	}
	
	var e = parent.document.getElementById("fpGalleryCaptionCell_2337")
	if (e) {e.innerHTML = c.title;}
}

function SetSlideShowInterval (Interval) {
	SlideShowInterval = Interval;
}

function nextSlide() {
 if (lastImg==(-1)) {return false};
 var imgs = thumbnail_frame.document.images;

	currentImgIndex = (currentImgIndex==lastImg) ? firstImg : (currentImgIndex+1);
	showSlide ();
	showImgTitle (imgs[currentImgIndex]);
}

function previousSlide() {
 if (lastImg==(-1)) {return false};
 var imgs = thumbnail_frame.document.images;

	currentImgIndex = (currentImgIndex==firstImg) ? lastImg : (currentImgIndex-1);
	showSlide ();
	showImgTitle (imgs[currentImgIndex]);
}

function showImg (Img) {
 var imgMain = parent.document.getElementById("fpGalleryMainImg_2337");
 	if (top.lastImg==(-1)) {return false};

	imgMain.src = Img.lowsrc;
//	imgMain.title = Img.title;
	imgMain.alt = Img.alt;
	imgMain.title="Click to add photo to shopping cart";

	if (Img.height==100) {
		{imgMain.style.width = 320;imgMain.style.height = 480}
	} else {
		{imgMain.style.width = 480;imgMain.style.height = 320}
	}
}

function showSlide() {
 if (lastImg==(-1)) {return false};
 var imgs =parent.window.thumbnail_frame.document.images;
 var Img = imgs[currentImgIndex];

	showImg (Img);
	return (imgs);
}

function showImgTitle (Img)  {
 if (lastImg==(-1)) {return false};
  var e = parent.document.getElementById("fpGalleryCaptionCell_2337")
// 	if (e) {e.innerHTML = Img.title;}
	if (e) {e.innerHTML = Img.alt;}
	parent.showPhotoInfo();
}

function runSlideShow () {
    if (lastImg==(-1)) {return false};
    SlideShow = true;
	currentImgIndex = (currentImgIndex==lastImg) ? 0 : currentImgIndex+1;
	var imgs = showSlide ();

	showImgTitle (imgs[currentImgIndex]);
	idSlideShowTimeout = setTimeout ('runSlideShow()', SlideShowInterval);
}

function stopSlideShow () {
	SlideShow = false;
	clearTimeout (idSlideShowTimeout);
}
