
// {{{ Litebox functions

function isLitebox() {

	return ( CardBox ? true : false );
}

function openLitebox() {

	var edit_image = $("edit_image");
	
		if (undefined != edit_image) {
	
		var cardbox = new CardBox();
	
		if (undefined != typeof(edit_image.rev) && "" != edit_image.rev) {
	
			var indexSeparator = edit_image.rev.indexOf(",");
		
			cardbox.setSize(parseInt(edit_image.rev.substring(0,indexSeparator)),parseInt(edit_image.rev.substring(indexSeparator+1)));
		
			delete(indexSeparator);
		}
						
		if (undefined != typeof(edit_image.title) && "" != edit_image.title) {
					
			cardbox.setTitle(edit_image.title);
		}
		
		cardbox.setTarget(edit_image.href);
		cardbox.setCloseButton(false);
		cardbox.setScrolling(false);
				
		cardbox.open();
	}
	else {
		
		throw "No DOM element found";	
	}
}

function closeLitebox() {

	CardBox.close();
}

// }}}

function loadPreview(campaign_id) {
	//alert('Here comes your sample vid soon');
}

function validate(value,type) {
	if (type == 'email') {
		var regex = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name|asia|jobs|mobi|travel))$/;
	}
	else if (type == 'phone') {
		var regex = /^(\+?)([0-9\s-]{6,20})$/;
	}

	return regex.test(value);
}

function loadCardPlayer(swf_location,storyboard_url,comm_url) {

	var width = ( "undefined" == typeof(playerDimensions) ?  "576" : playerDimensions[0]  );
	var height = ( "undefined" == typeof(playerDimensions) ?  "320" : playerDimensions[1] );

	swfobject.embedSWF(swf_location, "content_player", width, height, "8.0.0", "expressInstall.swf",{ storyboardUrl : storyboard_url, communicationUrl : comm_url },{ wmode : "transparent", play : "true", loop : "true", scale : "showall", devicefont : "false", id : "mailcast", name : "mailcast", menu : "true", allowFullScreen : "false", allowScriptAccess : "always", salign : "" });
	return false;
}

function validateUploadedImages(i) {

	this.i_el = i;

	if (this.i_el < window.img_upload) {

		new Ajax.Request("/scripts/getImage.php?user_id=" + window.user_id + "&image_id=" + this.i_el, {
							method: 'get',
							onComplete: function(ajax) {
											if ("1" != ajax.responseText) { $$(".err_upload")[this.i_el].show(); $("err_form").show();  }
											else { $$(".err_upload")[this.i_el].hide(); validateUploadedImages(this.i_el+1); }
									}
								}
							);
	}
	else { validateRecipientForm(); }
}

function validateRecipientForm() {

	window.recipientError = false;

		if (document.recipientForm.firstname) {
		
			if ("" == document.recipientForm.firstname.value) {
				$("error_recipient_firstname").show();
				window.recipientError = true;
			}
			else {
				$("error_recipient_firstname").hide();
			}
		}
		
		if (document.recipientForm.lastname) {
		
			if ("" == document.recipientForm.lastname.value) {
				$("error_recipient_lastname").show();
				window.recipientError = true;
			}
			else {
				$("error_recipient_lastname").hide();
			}
		}
		
		if (document.recipientForm.email) {
		
			if (!validate(document.recipientForm.email.value, "email")) {
				$("error_recipient_email").show();
				window.recipientError = true;
			}
			else {
				$("error_recipient_email").hide();
			}
		}
		
		if (document.recipientForm.phone_country && document.recipientForm.phone_ln) {
		
			if ("-1" == document.recipientForm.phone_country.value || !validate(document.recipientForm.phone_ln.value, "phone")) {
				$("error_recipient_phone").show();
				window.recipientError = true;
			}
			else {
				$("error_recipient_phone").hide();
			}
		}

		if (window.recipientError) {
			$("err_form").show();
		}
		else {
			$("err_form").hide();
		}

		if (!window.recipientError) {
			document.recipientForm.submit();
		}
}

Event.observe(window,"load",function() {

	// Top banner	else { return false; }
		swfobject.embedSWF("http://www.cardfish.com/static/swf/banner_card_bored.swf", "banner_top_content", "728", "90", "8.0.0", "expressInstall.swf",null,{ wmode : "transparent" });

	if (document.body.id == "index") {

		swfobject.embedSWF("http://www.cardfish.com/static/swf/frontPageVideo-1.0.swf", "content_introvideo", "576", "320", "8.0.0", "expressInstall.swf",{ locale : window.locale.locale, lng : window.locale.language },{ wmode : "transparent" });

		swfobject.embedSWF("http://www.cardfish.com/static/swf/cardGallery.swf", "content_cardgallery", "1019", "920", "8.0.0", "expressInstall.swf",{ xmlPath : "/api/cardGallery", locale : window.locale.locale, lng : window.locale.language },{ wmode : "transparent" });

	}
	else if (document.body.id == "card") {

		swfobject.embedSWF("http://www.cardfish.com/static/swf/sampleVideoPlayer.swf", "content_howtovideo", "576", "320", "8.0.0", "expressInstall.swf",{ campaignId : window.campaign_id, locale : window.locale.locale, lng : window.locale.language },{ wmode : "transparent" });

		swfobject.embedSWF("http://www.cardfish.com/static/swf/cardGallery_small.swf", "content_cardgallery", "600", "234", "8.0.0", "expressInstall.swf",{ xmlPath : "/api/cardGallery?type=small%26category_id="+window.category_id, category_id : window.category_id, locale : window.locale.locale, lng : window.locale.language },{ wmode : "transparent" });

		// {{{ Int'l dialing code replacement

		if (typeof(c_codes) != "undefined" && document.recipientForm.phone_country != undefined && document.recipientForm.phone_idd != undefined) {
			Event.observe(document.recipientForm.phone_country,"change",function() {
				
				var call_code = document.recipientForm.phone_country.options[document.recipientForm.phone_country.selectedIndex].value;
				
				document.recipientForm.phone_idd.value = ( window.c_codes[call_code] ? "+" + window.c_codes[call_code] : "" );
			});
		}

		// }}}

		// {{{ Validation

			if (document.recipientForm.email != undefined) {

				if (document.recipientForm.email) {
					Event.observe(document.recipientForm.email,"change",function() {
						if (!validate(this.value,"email")) { $("error_recipient_email").show(); }
						else { $("error_recipient_email").hide(); }
					});
				}
			}

			if (document.recipientForm.phone_ln != undefined) {

				Event.observe(document.recipientForm.phone_ln,"change",function() {
					if (!validate(document.recipientForm.phone_ln.value,"phone")) { $("error_recipient_phone").show(); }
					else { $("error_recipient_phone").hide(); }
				});
			}

		// }}}

		new DatePicker({
			relative: "date_input",
			keepFieldEmpty: true,
			dateFilter:DatePickerUtils.noDatesBefore(0).append(DatePickerUtils.noDatesAfter(365)),
			dateFormat:[ ["dd","mm","yyyy"], "/" ]
		});

		var variations = $$("ul#variations li a img");

		variations.each(function(el,index){

			Event.observe(el,"mouseover",function() {

				if (el.hasClassName("off")) { el.removeClassName("off"); }
				el.addClassName("on");

				variations.each(function(image_el,image_index){
					if (index != image_index) {
						if (image_el.hasClassName("on")) { image_el.removeClassName("on"); }
						image_el.addClassName("off");
					}
				});
			});

			Event.observe(el,"mouseout",function() {
				variations.each(function(el){
					if (el.parentNode.rel != window.campaign_id) {
						if (el.hasClassName("on")) { el.removeClassName("on"); }
						el.addClassName("off");
					}
					else {
						if (el.hasClassName("off")) { el.removeClassName("off"); }
						el.addClassName("on");
					}
				});
			});
		});

		if ($("show_upload_box")) {
			Event.observe($("show_upload_box"),"click",function() {
				if (this.href) { this.writeAttribute("href",null); }
				$("upload_box").show();
			});
		}

		$$("#content ul.delivery_time_type li").each(function(el,index) { // Click on the label have the affect too
			Event.observe(el,"click",function() {
				el.childElements().each(function(e) {
					if ("object" == typeof(e) && "input" == e.tagName.toLowerCase()) {
						e.checked = true;
						if ('0' == e.value) { // Hide date picker
							$("datetime_picker").hide();
						}
						else { // ... otherwise show it
							$("datetime_picker").show();
						}
					}
				});
			});
		});

		if ($("show_timezone_box")) {
			Event.observe($("show_timezone_box"),"click",function() {
				if (this.href) { this.writeAttribute("href",null); }
				$("timezone_box").show();
			});
		}

		Event.observe($("add_recipient_btn"),"click",function() {

			document.recipientForm.addrecipient.value = "1";

			if (0 < window.img_upload) { // test if all images are uploaded
				validateUploadedImages(0);
			}
			else { // ... or just validate the input fields
				validateRecipientForm();
			}
		});

		Event.observe(document.recipientForm,"submit",function() {

			if (0 < window.img_upload) { // test if all images are uploaded
				validateUploadedImages(0);
			}
			else { // ... or just validate the input fields
				validateRecipientForm();
			}
		});

		if ($$("#variations").length > 0) {

			load("http://www.cardfish.com/static/js/List-1.0.js");
			load("http://www.cardfish.com/static/js/storeFormValues-1.0.js");

			$$("#variations li a").each(function(element) {

				element.onclick = function() {

						var f = new storeFormValues("recipientForm");
						var json_form_values = f.set();

						new Ajax.Request("/scripts/storeFormValues.php", { method: 'post', postBody: "dataset=" + encodeURIComponent(json_form_values),
											onSuccess: function(ajax) {

												window.location = element.href;
											}
						});

					return false;
				};
			}
			);
		}
	}
	else if (document.body.id == "confirmation") {

		swfobject.embedSWF("http://www.cardfish.com/static/swf/cardGallery_small.swf", "content_cardgallery", "600", "234", "8.0.0", "expressInstall.swf",{ xmlPath : "/api/cardGallery?type=small", locale : window.locale.locale, lng : window.locale.language },{ wmode : "transparent" });

		// {{{ Int'l dialing code replacement

		if ("undefined" != typeof(c_codes) && document.senderForm && document.senderForm.phone_country && document.senderForm.phone_idd) {
			Event.observe(document.senderForm.phone_country,"change",function() {
				
				var call_code = document.senderForm.phone_country.options[document.senderForm.phone_country.selectedIndex].value;
				
				document.senderForm.phone_idd.value = ( window.c_codes[call_code] ? "+" + window.c_codes[call_code] : "" );
			});
		}

		// }}}

		Event.observe($$("#content_player img")[0],"click",function() {
			loadCardPlayer(url_swf,recipients[0].s,recipients[0].c);
		});

		$$("#recipients .tab .play").each(function(el,index) {
			Event.observe(el,"click",function() {
				el.writeAttribute("href",null);

				var place_img = false;

				if ("undefined" != typeof(preview_session_img)) {

					for (var i in preview_session_img) {

						if (index == preview_session_img[i]) {

							place_img = true;
							break;
						}
					}
				}

				if (place_img) {

					$$(".videoarea .contents .content")[0].innerHTML = '<div id="content_player"><img src="http://www.cardfish.com/static/img/preview_img_dontstripsanta.jpg" alt="Your Cardfish is ready - Click PREVIEW to check it out!" height="320" width="576" border="0" /></div>';
				}
				else {

					loadCardPlayer(url_swf,recipients[index].s,recipients[index].c);
				}
				
				return false;
			});
		});

		$$("#recipients .tab form.remove").each(function(el,index) {
			Event.observe(el,"submit",function() {

				var inputs = el.getElementsByTagName("input");
				if (inputs[3]) { inputs[3].value = "Removing..."; }

				new Ajax.Request("/scripts/recipient_manage.php",{
									method:'post',
									postBody:'method=remove&user_id='+el.user_id.value,
									onComplete:
										function(ajax,index) {
											if ("1" == ajax.responseText) {
												el.parentNode.parentNode.parentNode.parentNode.remove();
												if (0 == $$("#recipients div.tab").length) { // No recipients defined so redirect to the card creation page
													alert("You currently have no recipients so now you'll be sent back to the home page where you can create a new card");
													window.location = "/";
												}
												else { // Change recipient IDs
													delete(recipients[index]);
													$$("#recipients div.tab .content .edit").each(function(el,e_index) {
														el.href = el.href.replace(/(\d+)/,e_index);
													});
												}
											}
											else {
												inputs[3].value = "Remove";
												alert("Could not remove recipient, please try again");
											}
										}
									}
								);
			});
		});

		Event.observe(document.senderForm,"submit",function() {

			var senderError = false;
	
			if (document.senderForm.firstname) {
			
				if ("" == document.senderForm.firstname.value) {
					$("error_sender_firstname").show();
					senderError = true;
				}
				else {
					$("error_sender_firstname").hide();
				}
			}
			
			if (document.senderForm.lastname) {
			
				if ("" == document.senderForm.lastname.value) {
					$("error_sender_lastname").show();
					senderError = true;
				}
				else {
					$("error_sender_lastname").hide();
				}
			}
			
			if (document.senderForm.email) {
			
				if (!validate(document.senderForm.email.value, "email")) {
					$("error_sender_email").show();
					senderError = true;
				}
				else {
					$("error_sender_email").hide();
				}
			}
			
			if (document.senderForm.phone_country && document.senderForm.phone_ln) {
			
				if ("-1" == document.senderForm.phone_country.value || !validate(document.senderForm.phone_ln.value, "phone")) {
					$("error_sender_phone").show();
					senderError = true;
				}
				else {
					$("error_sender_phone").hide();
				}
			}
			
			if (senderError) {
				$("err_form").show();
			}
			else {
				$("err_form").hide();
			}
	
			if (!senderError) {
				document.senderForm.submit();
			}
		});
	}
	else if (document.body.id == "occasions") {

		if ($("content_new") && $("content_top")) {

			swfobject.embedSWF("/static/swf/cardGallery_1row.swf", "content_new", "1019", "180", "8.0.0", "expressInstall.swf",{ type : "new", locale : window.locale.locale, lng : window.locale.language },{ wmode : "transparent" });
			swfobject.embedSWF("/static/swf/cardGallery_1row.swf", "content_top", "1019", "180", "8.0.0", "expressInstall.swf",{ type : "topcards", locale : window.locale.locale, lng : window.locale.language },{ wmode : "transparent" });
		}
	}
	else if (document.body.id == "watch") {

		loadCardPlayer(url_swf,card_params.s,card_params.c);
	}
});

function load(url) {

	var scriptTag = document.createElement("script");
	scriptTag.src = url;
	scriptTag.type = "text/javascript";
	document.getElementsByTagName("head")[0].appendChild(scriptTag);
}