var ajaxUrl = '/cards/ajax/';
var cardChanged = false;
var lastTextSent = '';
var lastFieldSent = '';

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}



 
// Change the value of the outputText field **** For Testing *****

function setOutput(originalRequest) {
   
	$('outputText').innerHTML = originalRequest.responseText;
    
}
function LogMouseUpEvent(){
	thisMovie("dreamcards").LogMouseUpEvent();
	//thisMovie("dreamcards").ResetFlash();
	//alert("mouse up!");
}

function ResetFlash() {
    thisMovie("dreamcards").ResetFlash();
    $('cardThumbDiv').style.backgroundImage = "url(/"+ thumbArray[0]+")";
}

function ResetCard(){
	new Ajax.Request(ajaxUrl, 
	{
		method: 'get',
		parameters: 'clear=true',
		onSuccess: ResetFlash	
	});
	//$('draftId').value ='';
	//ResetFlash();
}

function updateActiveCard(cardId,updateType,updateNumber){
	new Ajax.Request(ajaxUrl, 
	{
		method: 'get',
		parameters: 'changeactive='+cardId+'updatetype='+updateType+'updatenumber='+updateNumber	
	});
}

function saveDraft(){
	if(cardChanged){
		cardChanged = false;
		$('saveDraftButton').hide();
		$('saveDraftSaved').hide();
		$('saveDraftParlor').show();
		//Effect.Fade('saveDraftButton', { duration: 0.2 ,queue: 'end' });
		//Effect.Appear('saveDraftParlor', { duration: 0.2 ,queue: 'end'});
		new Ajax.Request(ajaxUrl, 
		{
			method: 'get',
			parameters: 'save='+$F('draftId'),
			onSuccess: setDraftId
		});
	}
}

function setDraftId(originalRequest) {
	draftSavedState();
	
  	//Effect.Fade('saveDraftParlor', { duration: 0.2, queue: 'end'});
	//Effect.Appear('saveDraftSaved', { duration: 0.2,queue: 'end' });
	$('draftId').value = originalRequest.responseText.trim();
    
}

function draftSavedState(){
	$('saveDraftButton').hide();
	$('saveDraftParlor').hide();
	$('saveDraftSaved').show();
}

window.onload=initEditCards;

function initEditCards(){
	
	if(loggedIn){ 
	pe = new PeriodicalExecuter(getInboxUnread, 30); 
		getInboxUnread();
		
	
	}


	
	if ($('fromName') != null){
	
		if(loggedIn){ 
			draftSavedState();
		
		}
	
		if (returnType == 'reply'){
			setSubject('Re: ');
		}
		if (returnType == 'forward'){
			setSubject('Fwd: ');
		}
		
		if(typeof loggedIn != "undefined"){
			if(loggedIn){ 
				new PeriodicalExecuter(saveDraft, 60); 

			};
			
		}
		Event.observe(document,'mouseup',LogMouseUpEvent); 
		/* Event.observe($(''),'focus',LogMouseUpEvent); */
		
		setObserve('fromName', 'Name');
		setObserve('fromEmail', 'Email');
		setObserve('toName1', 'Name');
		setObserve('toEmail1', 'Email');
		setObserve('subject', false);
		/*

		Event.observe($('fromName'),'focus',focusField('Name',));
		Event.observe($('fromName'),'blur',blurName);
		Event.observe($('toName1'),'focus',focusName);
		Event.observe($('toName1'),'blur',blurName);
		
		Event.observe($('fromName'),'focus',focusEma);
		Event.observe($('fromName'),'blur',blurName);
		Event.observe(window,'focus',LogMouseUpEvent);
*/
		
	}
	
}
function getInboxUnread(){
	new Ajax.Request(ajaxUrl, 
	{
		method: 'post',
		parameters: 'getunread=',
		onSuccess: updateIndicator
		
	});
};

function updateIndicator(originalRequest) {
	//alert(originalRequest);
	pe.stop();
	pe = new PeriodicalExecuter(getInboxUnread, 30); 
	if (originalRequest.responseText.trim() >0  && $('ind_head_text').innerHTML != originalRequest.responseText.trim()){
		if ($('inboxIndNav')){
			$('inboxIndNav').show();
			$('inboxIndNav').innerHTML = '<strong>Inbox ( '+ originalRequest.responseText.trim()+' )</strong>';
		}
		$('ind_head').show();
		$('ind_head_text').innerHTML = originalRequest.responseText.trim();
	}else if (originalRequest.responseText.trim() == 0){
		$('ind_head').hide();
		if ($('inboxIndNav')){
			$('inboxIndNav').innerHTML = 'Inbox';
		}
	}
    
}


function setObserve(formName, defaultText){
	new Form.Element.DelayedObserver($(formName), .5, function(){
     	SaveFormInfo(formName)
    });
    Event.observe($(formName),'focus',function(){
     	if($F(formName) == 'Name' || $F(formName) == 'Email'){
     		$(formName).value = '';
     	}
    });
    
    Event.observe($(formName),'blur',function(){
     	if($F(formName) == '' && defaultText){
     		$(formName).value = defaultText;
     	}
     	if(lastFieldSent == formName && lastTextSent != $(formName).value){
     		SaveFormInfo(formName);
     	}
    });

     
}

function changeCardThumb(tempId) {
	$('cardThumbDiv').style.backgroundImage = "url(/"+ thumbArray[tempId]+")";
	$('cardThumbDivSendWindow').style.backgroundImage = "url(/"+ thumbArray[tempId]+")";

    $('tempId').value = tempId;
}

function SaveCardId(tempId) {

	changeCardThumb(tempId);
	
	new Ajax.Request(ajaxUrl, 
	{
		method: 'get',
		parameters: 'tempId='+tempId,
		onSuccess: setChanged 
	});
}

function switchFormVis(){
	Effect.Fade('readCard', { duration: 0.5 });
	Effect.Appear('writeForm', { duration: 0.5, queue: 'end'});
}

function replyCard(uniqueId){
	var curFrName = $F('fromName');
	var curToName = $F('toName1');
	var curFrEmail = $F('origFromEmail');
	var curToEmail = $F('toEmail1');
	
	var type = 'replysent';
	if (fromBox = 'inbox'){
		$('toName1').value = curFrName;
		$('toEmail1').value = curFrEmail;
		$('fromName').value = curToName;
		$('fromEmail').value = curToEmail;
		type = 'replyinbox';
	}

	switchFormVis();
	
	new Ajax.Request(ajaxUrl, 
	{
		method: 'get',
		parameters: 'act='+type+'&id='+uniqueId
	});
	
	thisMovie('dreamcards').SetEndState("reply");
	
	setSubject("Re: ");
	
	SaveFormInfo("fromName");
	SaveFormInfo("fromEmail");
	SaveFormInfo("toName1");
	SaveFormInfo("toEmail1");
	ViewToEdit();
}

function forwardCard(uniqueId){
	
	var curToName = $F('toName1');
	var curToEmail = $F('toEmail1');
	var type = 'forwardsent';
	
	if (fromBox = 'inbox'){
		$('fromName').value = curToName;
		$('fromEmail').value = curToEmail;
		type = 'forwardinbox';
	}
	
	switchFormVis()
	new Ajax.Request(ajaxUrl, 
	{
		method: 'get',
		parameters: 'act='+type+'&id='+uniqueId
	});

	thisMovie('dreamcards').SetEndState("forward");
	setSubject("Fwd: ");
	
	$('toName1').value = 'Name';
	$('toEmail1').value = 'Email';
	ViewToEdit();
	
	SaveFormInfo("fromName");
	SaveFormInfo("fromEmail");
	SaveFormInfo("toName1");
	SaveFormInfo("toEmail1");
}

function setSubject(kind){
	if ($('subject').value.lastIndexOf(kind)!= 0){
		$('subject').value = kind + $('subject').value;
		SaveFormInfo("subject");
	}

}

function SaveDrawingInfo(drawingData) {
   new Ajax.Request(ajaxUrl, 
   {
		method: 'post',
		parameters: 'drawingData='+drawingData,
		onSuccess: setChanged
  	});
}

function setChanged(){
//	if ($(saveDraftButton).style.display == "none"){
	
	$('saveDraftParlor').hide();
	$('saveDraftSaved').hide();
	$('saveDraftButton').show();
	//	}
	cardChanged = true;
}

function SaveTextInfo(textData) {    
    new Ajax.Request(ajaxUrl, 
   {
		method: 'post',
		parameters: 'textData='+textData,
		onSuccess: setChanged
  	});
}

function ViewToEdit() {
	thisMovie("dreamcards").ViewToEdit();
}


function SaveFormInfo(formName) {
	formValue = $F(formName);
	if ($F(formName) == 'Name' || $F(formName) == 'Email'  ) { 
	 	formValue ='';
	}
		lastFieldSent = formName;
		lastTextSent = formValue;
		new Ajax.Request(ajaxUrl, 
		{
			method: 'get',
			parameters: "formName="+formName+"&formValue="+formValue,
			onSuccess: setChanged
		});
		
		
	
}

function alertWindowOpen(){
	$('draftId').value ='';
	Effect.Fade('alertWindowSending', { duration: 0.1, queue: 'end'});
	Effect.Appear('alertWindowSent', { duration: 0.5, queue: 'end'});

}
function alertWindowClose(){
	Effect.Fade('modal', { duration: 0.9});
	Effect.Fade('alertWindowSent', { duration: 0.5});
	thisMovie("dreamcards").SetCursorState('true');

}



function sendCard() {
	//$('modal').style.height = getPageSize().pageH+'px'; 
	//$('modal').style.width = getPageSize().pageW+'px'; 
	
	cardChanged = false;
	if(loggedIn){
		draftSavedState();
	}
	thisMovie("dreamcards").SetCursorState();
	Effect.Appear('modal', { duration: 0.2});
	Effect.Appear('alertWindowSending', { duration: 0.3, queue: 'end'});

	//alertWindowOpen('alertWindowSending');
	new Ajax.Request(ajaxUrl, 
	{
		method: 'get',
		parameters: 'send='+$F('draftId'),
		onSuccess: alertWindowOpen
	});
	

}
function FlashSend() {
	verifyCard();
}

function FlashReply() {
	verifyCard();
}

function FlashForward() {
	verifyCard();
}


function closeAndReset(){
	ResetCard();
	alertWindowClose();
}



// verify card fields
function verifyCard() {
	var status = true;     
	var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
	if (document.cardCompose.fromEmail.value.search(emailRegEx) == -1) {
		alert("Please enter a valid 'from' email address.");
		status = false;
	} else if (document.cardCompose.toEmail1.value.search(emailRegEx) == -1) {
		alert("Please enter a valid 'to' email address.");
		status = false;
	} else if ($F('tempId') < 1) {
		alert("Please choose a card to send.");
		status = false;
	}
	//return status;
	if (status){
		sendCard();
	}
}
var cardsBusy = false;

function cardListSubmit(formName){
	//alert(formName);
	if (!cardsBusy){
		$(formName).submit();
	}
	cardsBusy = false;

}



function returnFromList(type,fieldName){
	//alert("<input id='returnType' type='hidden' name='returntype' value=''>");
	$(fieldName).value = type;
	

}

function deleteCardList(listId,fromBox){
	cardsBusy = true;
	$('del_'+listId).hide();
	$('delani_'+listId).show();
	new Ajax.Request(ajaxUrl, 
	{
		method: 'post',
		parameters: 'delete='+ listId + '&frombox='+ fromBox,
		onSuccess: function (transport){ 
		visualDeleteCard(listId);
		updateIndicator(transport);
		
		}
	});
	
}


function restoreCardList(listId,fromBox){
	//cardsBusy = true;
	new Ajax.Request(ajaxUrl, 
	{
		method: 'post',
		parameters: 'restore='+ listId + '&frombox='+ fromBox,
		onSuccess: function (transport){
			visualRestoreCard(listId);
			updateIndicator(transport);
		}
	});
	
}


function visualDeleteCard(listId){
	
	Effect.BlindDown('undo'+listId, { duration: .5 });
	Effect.BlindUp(listId, { duration: .2 });
	$('del_'+listId).show();
	$('delani_'+listId).hide();
	//updateIndicator(transport);
	//getInboxUnread();
}

function visualRestoreCard(listId){
	
	Effect.BlindUp('undo'+listId, { duration: .5 });
	Effect.BlindDown(listId, { duration: .5 });
	//getInboxUnread();
}


function verifyDiscard() {
	var status = false;
	var answer = confirm ("Do you really want to clear the contents of your card?")
	if (answer) {
		ResetCard();
		status = true;
	}
	//return status;
}

// for product rollovers // why is this in here?
var prodImages = [];

function showhideProd(layer_ref) {
	
	for(i=0; i < prodImages.length; i++) { 
   		$('img' + prodImages[i]).hide(); 
	}
	Effect.Appear(layer_ref, { duration: .5 });
	
}