// JavaScript Document
var gfcwFormAction = {
	currObjID: '',
	request: '',
	request_url: 'modules/request.php',
	formContainerID: '',
	
	formClear: function(recordID) {
			var objID = recordID != '' ? recordID : gfcwFormAction.currObjID;
			if(objID != '') {
				var objIDRow = '#rowID' + objID;
				$(objIDRow).css('background-color', '#FFF');
			}
			$('#editForm').html('<input type="button" value="add new" onclick="gfcwFormAction.showNew();"/>');
		},

	showNew: function(param, formActionRequest) {
			var objID = param;
			var objIDRow = '#rowID' + objID;
			var formActionRequest = formActionRequest != undefined ? formActionRequest : gfcwFormAction.request;
			$.ajax({
				url: gfcwFormAction.request_url,
				type: 'post',
				data: 'rqst=' + formActionRequest + '&objc=' + objID + '&actn=new',
    		beforeSend: function () { 
						if(gfcwFormAction.formContainerID) {
							$('html,body').animate({scrollTop: $(gfcwFormAction.formContainerID).offset().top},500);
 							$(gfcwFormAction.formContainerID).html('<p>завантаження форми даних...</p>');
						} else {
							$.facebox(function(){ })
						}
						},
				success: function(data) { 
						if(gfcwFormAction.formContainerID != '') {
							gfcwFormAction.formClear();
							$(gfcwFormAction.formContainerID).html(data);
						} else {
							$.facebox({ formHtml: data,
												  formExecClose: null,
												  formExecAccept: null
													})
						}
						}
			})
		},
	
	showUpdate: function(param, formActionRequest) {
			var objID = param;
			var objIDRow = '#rowID' + objID;
			var formActionRequest = formActionRequest != undefined ? formActionRequest : gfcwFormAction.request;
			$.ajax({
				url: gfcwFormAction.request_url,
				type: 'post',
				data: 'rqst=' + formActionRequest + '&objc=' + objID + '&actn=upd',
    		beforeSend: function () { 
						$(objIDRow).css('background-color', 'yellow');
						if(gfcwFormAction.formContainerID != '') {
							gfcwFormAction.formClear();
							$('html,body').animate({scrollTop: $(gfcwFormAction.formContainerID).offset().top},500);
 							$(gfcwFormAction.formContainerID).html('<p>завантаження форми даних...</p>');
						} else {
							$.facebox(function(){});
						}
						},
				success: function(data) { 
						if(gfcwFormAction.formContainerID != '') {
							gfcwFormAction.currObjID = objID;
							$(gfcwFormAction.formContainerID).html(data);
						} else {
							$.facebox({ formHtml: data,
												  formExecClose: function() { $(objIDRow).css('background-color', 'white'); },
												  formExecAccept: null
													});

						}
						gfcwFormAction.showOnLoad();
						}
			});
		},

	showDelete: function(param, formActionRequest) {
			gfcwFormAction.formClear();
			var objID = param;
			var objIDRow = '#rowID' + objID;
			var formActionRequest = formActionRequest != undefined ? formActionRequest : gfcwFormAction.request;
			$.ajax({
				url: gfcwFormAction.request_url,
				type: 'post',
				data: 'rqst=' + formActionRequest + '&objc=' + objID + '&actn=del',
				beforeSend: function () { 
						$(objIDRow).css('background-color', 'yellow');
						if(gfcwFormAction.formContainerID != '') {
							gfcwFormAction.formClear();
							$('html,body').animate({scrollTop: $(gfcwFormAction.formContainerID).offset().top},500);
 							$(gfcwFormAction.formContainerID).html('<p>завантаження форми даних...</p>');
						} else {
							$.facebox(function(){});
						}
						},
				success: function(data) { 
						if(gfcwFormAction.formContainerID != '') {
							gfcwFormAction.currObjID = objID;
							$(gfcwFormAction.formContainerID).html(data);
						} else {
							$.facebox({ formHtml: data,
												  formExecClose: function() { $(objIDRow).css('background-color', 'white'); },
												  formExecAccept: null
													});

						}
						gfcwFormAction.showOnLoad();
						}
				});
		},
		
	showOnLoad: function() { return true; },
	
	checkAll: function(element, checkClass) {
		$('.' + checkClass).attr('checked', element.checked);
		},

	/* initialization calendar component control 
		 showLinkID  - link ("A") or control ("INPUT") 
		               for show calendar component 
		 showValueID - "INPUT" control for show input value  */
	initCalendar: function(showLinkID, showValueID) {
		$(showLinkID).DatePicker({
			format:'Y-m-d',
			date: $(showValueID).val(),
			current: $(showValueID).val(),
			starts: 1,
			position: 'r',
			onBeforeShow: function(){
				if($(showValueID).val() != '') {
					$(showLinkID).DatePickerSetDate($(showValueID).val(), true);
				}
			},
			onChange: function(formated, dates){
				$(showValueID).val(formated);
				$(showLinkID).DatePickerHide();
			}
		})
		},

	initJQueryTinyMce: function() {
		$().ready(function() {
			$('textarea.tinymce').tinymce({
				// Location of TinyMCE script
				script_url : '/commons/jquery_tiny_mce/tiny_mce.js',
	
				// Example content CSS (should be your site CSS)
				content_css : "/commons/jquery_tiny_mce/css/content.css",
	
				// Drop lists for link/image/media/template dialogs
				template_external_list_url : "lists/template_list.js",
				external_link_list_url : "lists/link_list.js",
				external_image_list_url : "lists/image_list.js",
				media_external_list_url : "lists/media_list.js",
	
				// General options
				theme : "advanced",
				plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
	
				// Theme options
				theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
				theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
				theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
				theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				theme_advanced_statusbar_location : "bottom",
				theme_advanced_resizing : true,
	
				// Replace values for the template plugin
				template_replace_values : {
					username : "Some User",
					staffid : "991234"
				}
			});
		});
	},
	
	initJQueryTinyMceLite: function(textareaStyle) {
		$().ready(function() {
			$('textarea.' + textareaStyle).tinymce({
				// Location of TinyMCE script
				script_url : '/commons/jquery_tiny_mce/tiny_mce.js',
				mode : "textareas",
				theme : "advanced",
				plugins : "safari,table,advhr,advimage,advlink,inlinepopups,preview,print,contextmenu,paste,directionality,iespell,media,xhtmlxtras",
				theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,cut,copy,paste,pastetext,pasteword,|,bullist,numlist,visualchars,|,undo,redo,cleanup,|,forecolor,backcolor,",
				theme_advanced_buttons2 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,link,unlink,iespell,media,code,",
				theme_advanced_buttons3 : "",
				theme_advanced_buttons4 : "",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				theme_advanced_statusbar_location : "none",
				theme_advanced_resizing : true,
				extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name|style],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style],object[width|height|classid|codebase|embed|param],param[name|value],embed[param|src|type|width|height|flashvars|wmode],iframe[src|style|width|height|scrolling|marginwidth|marginheight|frameborder]", 
				media_strict: false,
				// Example content CSS (should be your site CSS)
				content_css : "/commons/jquery_tiny_mce/jquery.tinymce.css",
				// Drop lists for link/image/media/template dialogs
				template_external_list_url : "js/template_list.js",
				external_link_list_url : "js/link_list.js",
				external_image_list_url : "js/image_list.js",
				media_external_list_url : "js/media_list.js",
				// Replace values for the template plugin
				template_replace_values : {
					username : "Some User",
					staffid : "991234"
        	}
				})
			});		
		},
	
	/* добавляє поле вводу імені файлу */
	imgListInsert: function(listID, itemName, maxImage) {
		var i = $('ol#' + listID + ' li').size() + 1;
		var nameLI = itemName + i; 
		var func_param = '\'' + listID + '\', \'' + itemName + '\'';
		func_param += typeof(maxImage) != 'undefined' ? ', ' + maxImage	: '';
		var htmlLI = '<li><input name="' + nameLI + '" id="' + nameLI + '" type="file" value="" size="55" onchange="javascript:gfcwFormAction.imgListInsert(' + func_param + ');"></li>';
		if( (typeof(maxImage) == 'undefined') || (maxImage >= i) ) {
	    $(htmlLI).appendTo('ol#' + listID);
		}
		},
	
	/* видяляє поле вводу імені файлу */
	imgListRemove: function(listID) {
		$('ul#' + listID + ' li:last').remove();
		},

	/* видаляє піктограмку фотографії з  */
	imgListRemoveThumb: function(thumbID) {
		if( confirm('Ви дійсно хочете видалити фотографію?') ) {
			$('#galleryThumb_' + thumbID).remove();
			$('#gallery').append('<input name="galleryThumbDelete[]"  type="hidden" value="' + thumbID + '">');
			}
		}	
}

formValidator = {
	demo: function() {
		/* http://bytes.com/topic/javascript/answers/460516-check-file-size-javascript */
 extArray = new Array(".jpg", ".jpeg",".gif");  //".png", , ".gif"
  
 function callCancel()
 {
     document.frmlisting.action="listing_list.php?cityid=<?=$cityid?>&c_id=<?=$c_id?>";
     document.frmlisting.submit();
 }
  
 function callSave()
 {
 var oas = new ActiveXObject("Scripting.FileSystemObject");
 var d = document.frmlisting.txtlistingimage.value;
 var e = oas.getFile(d);
 var f = e.size;
 alert(f + "500000");
 }
 {
     if(!isCurrency(document.frmlisting.txtlistingprice.value)){
         alert("Price: Incorrect data");
         document.frmlisting.txtlistingprice.select();
         return;
     }
     if(isBlank(document.frmlisting.txtlistingtitle.value)){
         alert("Title is Required");
         document.frmlisting.txtlistingtitle.focus();
         return;
     }
     if(!isBlank(document.frmlisting.txtlistingimage.value)){
         if(!isValidFile(document.frmlisting.txtlistingimage.value)){
             alert("Selected file is not a vaild image type. \nPlease select "+ (extArray.join("  ").toUpperCase())+ " files. ");
             document.frmlisting.txtlistingimage.select();
             return;
         }
     }
     if(isBlank(document.frmlisting.txtlistingemail.value)){
         alert("Email is Required");
         document.frmlisting.txtlistingemail.select();
         return;
  
     }
     if(!isEmail(document.frmlisting.txtlistingemail.value)){
         alert("Email: Incorrect data");
         document.frmlisting.txtlistingemail.select();
         return;
     }
  
     document.frmlisting.action="listingsubmit.php";
     document.frmlisting.submit();
   }		
	}
}
