/****
*	Groupcards CSS Skin Loading & Reloading functions -GvH
*		on load, first skin will be doc.written, replacement is
*		done through ajax calls and adjusting the stylesheet 
*
*		XML string should look like this :
*		<css name="name of sheet"><classname_cssAttribute>cssAttributeValue</classname_cssAttribute>....</css>
*		Then docWriteSkin(stringToXML(stringCSS)) will write the initial css, loadSkin(stringCSS) will load a new skin
****/	
	var groupCardsCSS = new Array();
	
	function stringToXML (s) {
		if (navigator.appName.indexOf("Microsoft") > -1){
			  xmlCSS=new ActiveXObject("Microsoft.XMLDOM");
			  xmlCSS.async="false";
			  xmlCSS.loadXML(s);
		}
		else {
			var xmlCSS = (new DOMParser()).parseFromString(s, 'application/xml');
		}
		return xmlCSS;
	}
		
	function parseCSSRule (xmlCSS) {
		//returns array with element,attribute and attribute value
		var aNode = xmlCSS.nodeName.split("_");
		var element = aNode[0];
		var attribute = aNode[1];
		if (!xmlCSS.childNodes[0])
			var value = "";
		else
			var value =xmlCSS.childNodes[0].nodeValue;
		
		// Exceptions		
		if (element == "GCLink") {
			if (attribute == 'color' && value != ""){
				value = value+"!important";
			}
			else if (attribute == 'background-color' && value == ""){
				value = "transparent";
			}
		}		
		else if (attribute == "background-image" && value != "") {
			value = "url(http://ak.imgfarm.com/images/fwp/myfuncards/GroupCards/" + value + ")" ;
		}
		else if (attribute == "opacity" && value != "") {
			//console.log(attribute + value);
			if (value.indexOf("%") > 0 )
				value = value.replace("%","") * 1;
			else
				value = value * 1;
			
			if (navigator.appName.indexOf("Microsoft") > -1){
				attribute = "filter";
				value = "alpha(opacity="+(value * 100)+")";
			}
			else {
				value = value + "";
			}			
		}
		return [element,attribute,value];
	}
	
	function docWriteSkin(xml) {
		var cssRoot = xml.childNodes[0];
		var nodes = cssRoot.childNodes.length;
		var styleName = cssRoot.attributes.getNamedItem("name").value
		document.write('<style title="skinCss" name="' + styleName + '">')
		for (var i = 0 ; i < nodes ; i++){
			var aCSS = parseCSSRule(cssRoot.childNodes[i]);
			document.write(
				"." + aCSS[0] + "{" + aCSS[1] + ":" + aCSS[2] + ";}"		
			)
		}
		document.write('</style>')	
	}
	
	function getAjaxSkin(sSkinName) {
		var saveUrl = "templateService.jhtml?assetId="+sSkinName + "&unregId=" + oHtmlMenuCtl.id;
		if (CardId)
			saveUrl += "&c=" + CardId;
		else 
			saveUrl += "&cat=" + groupCardsCatId + "&subcat=" + groupCardsSubCatId;
		jQuery.getJSON(saveUrl, function(data) {
			if (data.error == ""){
				if (data.cardid != ""){
					CardId = data.cardid;
				}
				// Save css to avoid future ajax calls
				if (groupCardsCSS[data.id] == undefined) {					
					groupCardsCSS[data.id] = data.clob;
				}				
				TemplateId = data.id;
				jQuery('input[@name=assetId]').attr('value',data.id);		
				testCSS = data.clob;
				loadSkin(data.clob);
				toggleSelect(true);	
			}
			else {
				toggleSelect(true);	
				// display error and set selectbox back
			}			
		
		});
	}				
	
	function loadSkin(s) {
		var xmlCSS = stringToXML(s);
		if (navigator.appName.indexOf("Microsoft") > -1)
			loadSkinIE(xmlCSS);
		else
			loadSkinFF(xmlCSS);
		setTimeout ("setRTEFont()",200);
	}
	
	function loadSkinFF(xml) {
		var cssRoot = xml.childNodes[0];
		var nodes = cssRoot.childNodes.length;
		var styleName = cssRoot.attributes.getNamedItem("name").value
		var newSkin = "";
		for (var i = 0 ; i < nodes ; i++){
			var aCSS = parseCSSRule(cssRoot.childNodes[i]);				
			newSkin += "." + aCSS[0] + "{" + aCSS[1] + ":" + aCSS[2] + ";}\n";
		}
		jQuery('style[@title=skinCss]').html(newSkin);
		jQuery('style[@title=skinCss]').attr('name',styleName);
		return true;
	}	
	
	function loadSkinIE(xml) {
		var cssRoot = xml.childNodes[0];
		var nodes = cssRoot.childNodes.length;
		var styleName = cssRoot.attributes.getNamedItem("name").value
		var iStyleSheets = document.styleSheets.length;
		for (var i = 0 ; i < iStyleSheets ; i++ ) {
			if (document.styleSheets[i].title == "skinCss"){
				var oStyleSheet=document.styleSheets[i];
			}
		}
		if (oStyleSheet == undefined) {
			return false; // couldn't get skin
		}
		var oRule=oStyleSheet.rules[0];		
		for (var i = 0 ; i < nodes ; i++){
			var aCSS = parseCSSRule(cssRoot.childNodes[i]);
			oStyleSheet.addRule("."+aCSS[0],aCSS[1]+": " + aCSS[2] +";");
		}
		jQuery('style[@title=skinCss]').attr('name',styleName);
		return true;
	}
	
	function unloadSkin(name) {
		// removes Skin
		if (jQuery('style[@name ='+name+']').length > 0){
			jQuery('style[@name ='+name+']').remove();
			return true;
		}
		else {
			return false;
		}	
	}
	
	function getCurrentSkin() {
		// returns name of stylesheet with title 'skinCss'
		if (jQuery('style[@title=skinCss]').length > 0) {
			return jQuery('style[@title=skinCss]').attr('name');
		}
		else
			return null;
	}
	
	function changeTemplate() {
		var template = jQuery('#templateSelect option:selected').attr('value');
		if (groupCardsCSS[template] != undefined){
			loadSkin(groupCardsCSS[template]);
			jQuery('input[@name=assetId]').attr('value',template);	
		}
		else {
			getAjaxSkin(template);
			toggleSelect(false);	
		}
	}
	
	function toggleSelect(enabled) {
		jQ = jQuery("#templateSelectBox");
		jQparent = jQuery("#templateSelect");
		if(enabled) {
			jQparent.children('.loading').fadeOut();
			jQ.attr('disabled',false);
			jQparent.children('span:first').html('Template:');
		}
		else {
			jQparent.children('span:first').html('Loading...');
			jQ.attr('disabled',true);
			jQparent.children('.loading').fadeIn();
		}
	}
	
	function editLink(divId,callingLink){
		//saveOpenFields(callingLink); 
		if(callingLink){
			toggleLink(callingLink);		
			var jQ = jQuery('#' + divId);

			if (jQ.hasClass('editable')) {
				switchEditable(divId,false);
				saveAjaxField(divId);
			}
			else 
				switchEditable(divId,true);
		}
		
	}
	
	function switchEditable (divId,b) {
		var jQ = jQuery('#' + divId);
		DEBUG(jQ);
		if (b) {
			jQ.removeClass('notEditable');	
			jQ.addClass('editable');
			//jQ[0].disabled = false;
			jQ[0].focus();
		}
		else {
			jQ.removeClass('editable');	
			jQ.addClass('notEditable');
			//jQ[0].disabled = true;
		}	
	}
	
	function toggleRTE(callingLink) {
		var jQ = jQuery('#rte iframe');
		if (callingLink)
			toggleLink(jQuery('#RTESaveLink')[0]);
			
		if (jQ.hasClass('editableRTE')) {
			jQ.designMode('off');
			jQ.removeClass('editableRTE');
			jQ.removeClass('GCForm');
			jQ.prev('div').hide();	
			jQuery('#message').val(jQuery('#rte').richText());
			saveAjaxValue('message', jQuery('#rte').richText()); 
			jQuery(jQuery('#rte iframe')[0].contentWindow.document.body).css('background-color','transparent')
		}
		else {
			jQ.designMode('on');
			jQ.addClass('editableRTE');
			jQ.addClass('GCForm');
			jQuery(jQuery('#rte iframe')[0].contentWindow.document.body).css('background-color','papayawhip')
			jQ.prev('div').show();
		}	
	}
		function toggleLink(link) {
			if (link){
				var jQ = jQuery(link);
				if (jQ.hasClass('savingLink')) {
					jQ.removeClass('savingLink');
					jQ.hide().fadeIn();
					jQ.html('[edit]');		
				}
				else {
					jQ.addClass('savingLink');
					jQ.hide().fadeIn();
					jQ.html('[save]');
				}
			}
		}
	function saveOpenFields (except) {
		// Check inputs
		var l = jQuery('.editableFormField input.editable').length;
		for (i = 0 ; i < l ; i++) {
			var jqE = jQuery('.editableFormField input.editable:eq('+i+')');
			var jqEParent = jqE.parent();
			var jqELink = jqEParent.children('a')[0];
			if (except != jqELink)
				editLink(jqE.attr('id'),jqELink);
		}
		// Check textareas
		var l = jQuery('.editableFormField textarea.editable').length;
		for (i = 0 ; i < l ; i++) {
			var jqE = jQuery('.editableFormField textarea.editable:eq('+i+')');
			var jqEParent = jqE.parent();
			var jqELink = jqEParent.children('a')[0];
			if (except != jqELink)
				editLink(jqE.attr('id'),jqELink);
		}
		//Check RTE
		var jQ = jQuery('#rte iframe');
		if (except != "RTE" && jQ.hasClass('editableRTE')) {
			toggleRTE('RTE');
		}
	}
	function saveAjaxValue(fieldName, fieldValue) {
		//remove errors if present:
		jQuery('#ajaxError'+fieldName).remove();
		jQuery('#submitError'+fieldName).remove();
		
		var saveUrl = "groupCardFieldEdit.jhtml?unregId=" + oHtmlMenuCtl.id + "&";
		if (CardId)
			saveUrl += "c=" + CardId + "&";
		else 
			saveUrl += "assetId=" + TemplateId + "&"
		saveUrl +="fieldName=" + fieldName + "&fieldValue=" + escape(fieldValue);
		saveUrl += "&cat=" + groupCardsCatId + "&subcat=" + groupCardsSubCatId;
		jQuery.getJSON(saveUrl, function(data) {
			if (data.result == "success") { //(false){//
				CardId = data.cardid;
				document.forms['groupCardEdit'].cardId.value = CardId;
				if (data.cardstatus != "") 
					 document.forms['groupCardEdit'].cardStatus.value = data.cardstatus;	
			}
			else {
				jQuery("#previewContainer").hide();	//hide preview link
				var errorMsg = data.result;
				// make messages friendlier
				if(fieldName == 'recName') {
					errorMsg = "Please enter a valid Name below.";
				}
				else if(fieldName == 'title') {
					errorMsg = "Please enter a valid Card Title below.";
				}				
				else if(errorMsg.indexOf('can not be null') > -1)
					errorMsg = "oops! the field below should not be left empty.";
				else if (errorMsg.indexOf('Invalid email address') > -1)
					errorMsg = "Please enter a valid Email Address below";
				
				if (fieldName != "message") {
					jQuery('input[@name=' + fieldName + '],textarea[@name='+ fieldName +']').parent().prev().before('<div id="ajaxError'+fieldName +'" class="formError">'+errorMsg+'</div>')
				}
				else {
					jQuery('#RTESaveLink').before('<div id="ajaxError'+fieldName +'" class="formError">'+errorMsg+'</div>')
				
				}
			}
			
			togglePreviewLink();
		});
	}
	function saveAjaxField(divId) {
		var fieldName = jQuery("#"+divId)[0].name;
		var fieldValue = jQuery("#"+divId).val();
		saveAjaxValue(fieldName, fieldValue);
	}
	
	function toggleAds(b){
		if (b){
			jQuery('#adHeader').hide();
			jQuery('#adSkyscraper').hide();
		}
		else {
			jQuery('#adHeader').show();
			jQuery('#adSkyscraper').show();
		}
	}
	
	
// End Groupcards CSS Skin functions

toggleNext =  function(enabled,returning) {
	if (enabled){
		// Enable Next or Save Button
		if(jQuery('.Next').length > 0)
			jQuery('.Next').removeClass('disabled')[0].disabled = false;
		else if (jQuery('.Save').length > 0)
			jQuery('.Save').removeClass('disabled')[0].disabled = false;		
	}
	else {
		// Disable Next or Save Button
		if(jQuery('.Next').length > 0)
			jQuery('.Next').addClass('disabled')[0].disabled = true;
		else if (jQuery('.Save').length > 0)
			jQuery('.Save').addClass('disabled')[0].disabled = true;			
	}
	if(returning)
		return true;
}

function autoWrapCommas(src) {
	var emails = src.value; 
	emails = emails.replace(/,(?! )/g, ", ");
	src.value = emails;
}

function toggleUpload(state){

	document.forms['groupCardEditForm'].wizardCustomImage.value=state;
	
	if(state=="upload"){
		$("#uploadRadio1").attr("checked","checked");
		$("#uploadUrl1").removeAttr("checked");
	}
	else{
		$("#urlRadio1").attr("checked","checked");
		$("#uploadRadio1").removeAttr("checked");
	}
}

function stepLinkSubmit() {
	if (GCEditSubmit(true)) {
		formFinalize();						
	}
}

function deleteParticipantComment(pid) {
	jQuery('#participant_reqtype')[0].value = 2;
	jQuery('#participant_pid')[0].value = pid;
	jQuery('#groupCardEditForm').submit();
				
}	
/*This function submits the groupcard form as either preview or save mode depending on parameter*/	
function GCEditSubmit(submitType, cardId){
	 var preview; 
	 // signName and sendName are combined with MFC-481 , fill in signName with sendName
	 jQuery('#signName').val(jQuery('#editform_senderName').val());
	 
	 switch(submitType){
		//fill in hidden field to differ between save card & preview card
		case "preview":	
			preview = window.open ("about:blank", "preview","location=1,status=1,scrollbars=1,resizable=1,width=740,height=650");
			jQuery('#previewSubmit').attr('value',"true");
			document.forms["groupCardEditForm"].target="preview";
			preview.focus();
		break;
		
		case "save":
			jQuery('#previewSubmit').attr('value','');
			jQuery('#sendCard').attr('value',"");	
			document.forms["groupCardEditForm"].target="";
		break;
		
		case "submit":
			//jQuery("#signName").val(jQuery("#editform_participants").val());
			//jQuery("#signMessage").val(jQuery("#editform_participants").val());		
			jQuery('#previewSubmit').attr('value','');
			jQuery('#sendCard').attr('value',"true");	
			document.forms["groupCardEditForm"].target="";
		break;
	}
		
	//checks for a blank value in the card status	
	if($("#editform_cardStatus").val()=="")
		$("#editform_cardStatus").val(3);
		
			
	//jQuery('#previewSubmitExtra').attr('value',sPreview)
	//copy rte to inputfield (urlencode?)
	jQuery('#message')[0].value = jQuery('#rte').richText();
	
	var errorsFound = false;
	for(i in GroupCardWizard.cardData){
    	if(GroupCardWizard.cardData[i].value==""){
	    	errorsFound = true;
	    	break;
    	}
	}
	/* dev already checks this
		var jQE = jQuery('#editform_senderEmail')
		var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
		if (!filter.test(jQE.val())) {
			GCEditFormError("Your email address is invalid.",jQE);
			errorsFound = true;
		}	
		jQE = jQuery('#editform_recEmail')
		if (!filter.test(jQE.val())) {
			GCEditFormError("The recipient email address is invalid.",jQE);
			errorsFound = true;
		}
	*/
	if(!errorsFound && submitType!="preview") {
		if(jQuery('.Next').length > 0)
			jQuery('.Next').addClass('disabled')
		else if (jQuery('.Save').length > 0)
			jQuery('.Save').addClass('disabled')
		if(cardId) {
			$.ajaxSetup( { async: false });
			$.get(
				"/myfuncards/addToPopularity.jhtml",
				{
					cardId: cardId
				},
				function(data, status) {					
					
				}
			);	
			$.ajaxSetup( { async: true });			
		}
	}

	return !errorsFound;

}

function setRTEFont (){
	jQuery('#rte iframe')[0].allowTransparency = true;
	var textColor = jQuery('.GCText').css('color');
	var textFontFamily = jQuery('.GCText').css('font-family');
	var textFontSize = jQuery('.GCText').css('font-size');
	jQuery(jQuery('#rte iframe')[0].contentWindow.document.body).css('color',textColor).css('font-family',textFontFamily).css('font-size',textFontSize); //.css('background-color','transparent');
	jQuery(jQuery('#rte iframe')[0].contentWindow.document.body).css('background-color','transparent')				
}


function setSelectedSkin () {
	sSkin = getCurrentSkin();
	jQuery('#templateSelect');
}

function GCEditFormError(msg,jQE) {
	//display formError
	jQE.parent().prev().before('<div id="submitError'+ jQE[0].name +'" class="formError">'+msg+'</div>')
	// open to edit
}

function saveDate(){
	var dateString = jQuery('#editform_sendDateString').val() + "/" + jQuery('#editform_sendTimeHour').val() + "/"  + jQuery('#editform_sendTimeMin').val() + "/"  + jQuery('#editform_sendTimeMeridian').val() 
	//alert(dateString);
	$("#editform_formattedDateString").val(dateString);
	saveAjaxValue("sendDate", dateString);
}

/** this function is used to get a card id by submitting a field to the server before submitting the whole form*/
function formFinalize() {
	//TODO:  Don't submit date like this anymore.  This is a workaround for the demo
	saveDate();
	//jQuery(".inPlaceEditField").attr("disabled", false);
	window.setTimeout("document.forms['groupCardEdit'].submit()", 1500);
		return false;
}


/*** group card participant object and functions */
var GroupCardParticipant = {
	photoUrls: [],
	init: function() {
		GroupCardParticipant.setUploadFormInfo();
		
		jQuery("#btnSave").click(function(){
			jQuery("#formMain input[name='signName']").val(jQuery("#participantName").val());
			jQuery("#formMain input[name='signMessage']").val(jQuery("#participantMessage").val());
			toggleNext(false);
			
			if (jQuery('#uploadRadio')[0].checked)
				fieldId = 'uploadRadio';
			else if (jQuery('#urlRadio')[0].checked)
				fieldId = 'urlRadio';
			
			if (jQuery('#'+fieldId+ "~form>input:first")[0].value!= "" && !recentUploadDone){
				recentUploadDone = true;
				submitAfterUpload = true;
				// autoupload
				if (fieldId == 'uploadRadio')
					jQuery("#formUpload").submit();
				else if  (fieldId == 'urlRadio')
					jQuery("#formUrl").submit();
				return false;
			}
			else {
				jQuery("#formMain").submit();
			}
		});
	
		//handles the file upload on the form
		jQuery("#formUpload").ajaxForm({
			beforeSubmit: function(data, form, options) {								
				if(jQuery.trim(jQuery("#formUpload input[name='Filedata']").val()) == "") {				
					return false;				
				}
				toggleParticipantImageUploading(true,false);
				toggleNext(false);
			},
			success: function(responseText, statusText) {					
				GroupCardParticipant.setMainFormInfo();
				GroupCardParticipant.updateThumbnail();
				toggleParticipantImageUploading(false,false);
				recentUploadDone = true;
				toggleNext(true);
				if (submitAfterUpload){
					submitAfterUpload = false;
					jQuery("#formMain").submit();
				}
			}
		});
		
		//handles the URL Image getter
		jQuery("#formUrl").ajaxForm({
			beforeSubmit: function(data, form, options) {	
				if(jQuery.trim(jQuery("#formUrl input[name='url']").val()) == "") {				
					return false;				
				}
				toggleParticipantImageUploading(true,false);
				toggleNext(false);	
			},
			//callback function for AJAX form submission
			success: function(responseText, statusText) {					
				GroupCardParticipant.setMainFormInfo();
				GroupCardParticipant.updateThumbnail();
				toggleParticipantImageUploading(false,false);
				recentUploadDone = true;
				toggleNext(true);
				if (submitAfterUpload){
					submitAfterUpload = false;
					jQuery("#formMain").submit();
				}
			}
		});
		//sets up the parameters necessary to remove the signer image for group card participants
		jQuery("#removeImage").click(function() {
			GroupCardParticipant.clearMainFormInfo();
			//if a group card particpant, resets to ddefault thumbnail
			GroupCardParticipant.setThumbnail();
			//if the creator, resets to default thumbnail
			toggleParticipantImageUploading(false,true);
			toggleNext(true);
			jQuery("#removeImageParam").val("true");
			jQuery("#participant_pid").val("");	
			
			//will only work for other partipants, not the creator
			try{ document.forms["formMain"].toolbarId.value=""; }
			catch(exception){ 
				jQuery("#formMain_creatorThumbnail").css("backgroundImage","");
				document.getElementById("groupCardEditForm").toolbarId.value="";	
			}
		});
		
		jQuery("input:radio[name='imageSource']").click(GroupCardParticipant.setRadioButtons);
		GroupCardParticipant.setRadioButtons();			
	},
	
	setRadioButtons: function() {		
		if(jQuery("input:radio[name='imageSource'][checked]").length > 0) {	
			switch(jQuery("input:radio[name='imageSource'][checked]").val().toUpperCase()) {				
				case "UPLOAD":
					jQuery("#formUrl input").attr("disabled", true);
					jQuery("#formUpload input").removeAttr("disabled");
					break;
					
				case "URL":						
					jQuery("#formUpload input").attr("disabled", true);
					jQuery("#formUrl input").removeAttr("disabled");				
					break;
			}			
		}
	},
	
	//fills form elements with necessary data to save on the server every time a file is uploaded
	setUploadFormInfo: function() {
		var random = Math.floor(Math.random()*10000000+1);		
		jQuery("#formUpload input[name='uid']").val(oToolbarController.sUID);
		jQuery("#formUrl input[name='uid']").val(oToolbarController.sUID);
		jQuery("#formUpload input[name='fid']").val(random);			
		jQuery("#formUrl input[name='fid']").val(random);
	},
	
	setMainFormInfo: function() {
		jQuery("#formMain input[name='toolbarId']").val(oToolbarController.sUID);
		jQuery("#formMain input[name='photoId']").val(jQuery("#formUpload input[name='fid']").val());
	},
	
	clearMainFormInfo: function() {
		jQuery("#formMain input[name='toolbarId']").val("");
		jQuery("#formMain input[name='photoId']").val("");
	},
	
	setThumbnail: function(imgUrl) {		
		if(imgUrl) {
			jQuery("#participantThumbnail img").remove();
			jQuery("#participantThumbnail")
				.removeClass("GCDefaultPhoto")
				.append("<img src='" + imgUrl + "?r=" + Math.floor(Math.random()*10000000+1) + "' alt='' />");
		} else {
			jQuery("#participantThumbnail img").remove();
			jQuery("#participantThumbnail").addClass("GCDefaultPhoto");
		}						
	},
	
	updateThumbnail: function() {			
		jQuery.get(		
			"/upload/uploadUrl.jhtml?" + "uid=" + jQuery("#formMain input[name='toolbarId']").val() + "&fid=" + jQuery("#formMain input[name='photoId']").val() + "&n=2",
			function(response) {
				GroupCardParticipant.photoUrls = [
					response.getElementsByTagName("tempurl").length > 0 ?
						response.getElementsByTagName("tempurl")[0].firstChild.data
						:
						""
					,
					response.getElementsByTagName("tempurl1").length > 0 ?
						response.getElementsByTagName("tempurl")[0].firstChild.data
						:
						""
				];											
				GroupCardParticipant.setThumbnail(GroupCardParticipant.photoUrls[0]);										
			}
		);
	}
};

function toggleParticipantImageUploading(uploading,reset) {
	if (uploading) {
		jQuery('#participantThumbnail').removeClass('GCParticipant').addClass('uploading');
	}
	else {
		jQuery('#participantThumbnail').removeClass('uploading');
		if (reset){
			jQuery('#participantThumbnail').addClass('GCParticipant').html("");				
		}
	}	
}

/*to prevent a broken preview link, this function checks to see whether certain fields are entered 
before displaying the preview link*/
function togglePreviewLink(){
	if((GroupCardWizard.cardData.senderName.value!="" && GroupCardWizard.cardData.title.value!="") ||  document.forms['groupCardEdit'].cardStatus.value==3)
		jQuery("#previewContainer").show();
	else
		jQuery("#previewContainer").hide();
}
