var actionChoise='';
var domainName='';
var mypath='';
var hddlSTAct='';
//============================ common functions ================================
function validate(skineditor){
	//==== validate the controls ========================================================
	cssValue = getCheckedValue(skineditor("#formEdit input[name=csslevel]"));
	switch(cssValue)
	{
		case 'custom':
			document.getElementById("error_message").innerHTML="";
			break;
		case 'subtheme':
			cntr = getSelectedName(document.getElementById("ddlSTEdit"),true);												
			if(cntr == 'select' || cntr == 0){
				document.getElementById("error_message").innerHTML="<div style=\'color: #111111\' class=\'error\'>Please select a sub theme </div>"
			}else{
				document.getElementById("error_message").innerHTML="";
			}
			break;
		case 'variation':
			cntr = getSelectedName(document.getElementById("ddlVEdit"),true);												
			if(cntr == 'select' || cntr == 0){
				document.getElementById("error_message").innerHTML="<div style=\'color: #111111\' class=\'error\'>Please select a variation </div>"
			}else{														
				document.getElementById("error_message").innerHTML="";
				skineditor("#formEdit input[name=optFiles]")[0].checked = true;
			}			
			break;													
		case 'sitelevel':
			cntr = getSelectedName(document.getElementById("ddlUrlEdit"),true);												
			if(cntr == 'select' || cntr == 0){
				document.getElementById("error_message").innerHTML="<div style=\'color: #111111\' class=\'error\'>Please select a domain </div>"
				break;
			}		
			cntr = getSelectedName(document.getElementById("ddlSTEdit"),true);												
			if(cntr == 'select' || cntr == 0){
				document.getElementById("error_message").innerHTML="<div style=\'color: #111111\' class=\'error\'>Please select a sub theme </div>"
				break;
			}
			cntr = getSelectedName(document.getElementById("ddlVEdit"),true);												
			if(cntr == 'select' || cntr == 0){
				document.getElementById("error_message").innerHTML="<div style=\'color: #111111\' class=\'error\'>Please select a variation </div>"
				break;
			}
			document.getElementById("error_message").innerHTML="";
			break;
		default:
			document.getElementById("error_message").innerHTML="<div style=\'color: #111111\' class=\'error\'>please select a Customization level option </div>";
		break;
		
	}
	if(document.getElementById("error_message").innerHTML==""){
		return true;
	}
	clearAllRadios(skineditor("#formEdit input[name=optFiles]"));
	return false;
	//===============================================================================
}
function getSelectedName(ddl, getvalue){
	var myVal;
	if(getvalue==undefined)getvalue = false;
	if(ddl == undefined || ddl == null )return 0;
	if(getvalue){
		myVal = ddl.options[ddl.selectedIndex].value;
	}else{
		myVal = ddl.options[ddl.selectedIndex].text;
	}
	if(myVal=='')
	{
		myVal = '0';
	}
	return myVal;
}
function clearAllRadios(radList) {
	for (var i = 0; i < radList.length; i++) {
		radList[i].checked = false;
	}
}
function getCheckedValue(radioObj) {
	if(!radioObj)
		return false;
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return false;
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return false;
}
(
	function(skineditor){
		skineditorObj = 
		{
			flagAddVariationDropdownEventDone: false,
            init : function(){
				if(skineditor("#txtSubTheme").html() == null){
					return;
				}
				 skineditor("#skineditor_admin").tabs({selected: 2 //default tab
                                                    });
	//=================== set up object for add sub theme form =====================================================================
				var f = skineditor("#frmAddSTheme form");
				f.submit(function(){
										skineditorObj.ajaxSaveFile(this);
										return false;
									});										
				skineditor("#btSubTheme").click(function(){											
											actionChoise = '&actionChoise=addSubTheme';
											if(skineditor("#frmAddVariation select[name=ddlVAct]").html() !== null ){
												document.getElementById("ddlVAct").selectedIndex = 0;
												document.getElementById("btActivate").style.display = "none";
											}
											f.submit();
											return true;
										});
				skineditor("#btActs").click(function(){											
											skineditorObj.ajaxActivateSubtheme(document.getElementById("txtSubTheme").value);
											return true;
										});
										
	//=================== set up object for add sub variation form ===================================================================
				var g = skineditor("#frmAddVariation form");
				g.submit(function(){										
										skineditorObj.ajaxSaveFile(this);
										return false;
									});						
				skineditor("#btVariations").click(function(){
											actionChoise='&actionChoise=addVariation';
											hddlSTAct='&hddlSTAct='+getSelectedName(document.getElementById("ddlSTAct"),true);
											if(skineditor("#frmAddVariation select[name=ddlVAct]").html() !== null ){
												document.getElementById("ddlVAct").selectedIndex = 0;
												document.getElementById("btActivate").style.display = "none";
											}
											g.submit();
											return true;
										});
                if(skineditor("#frmAddVariation select[name=ddlSubThemes]").html() !== null){
					skineditorObj.addVariationDropdownEvent();
                    skineditorObj.flagAddVariationDropdownEventDone = true;
				}
				 
	//=================== set up object for activate theme form ========================================================================
				var h = skineditor("#frmActivate form");
				h.submit(function(){
										skineditorObj.ajaxSaveFile(this);
										return false;
									});										
				skineditor("#btActivate").click(function(){	
											actionChoise='&actionChoise=activate';											
											//==== activate the sub theme first ===================================================
											var hiddenUrl = document.getElementById("subThemeActivate").value;
											if(!hiddenUrl==''){
												win = window.open(hiddenUrl, 'mywindow', 'width=500, height=500, scrollbars=1');
											}
											//===============================================================================
											h.submit();
											return true;
										});
				skineditor("#btDeactivate").click(function(){	
											actionChoise='&actionChoise=deactivate';
											h.submit();
											return true;
										});
				skineditor("#formActivate input[name=txtUrl]").keydown(function(){
											actionChoise='&actionChoise=fill';
											h.submit();											
											return true;
										});
				skineditor("#formActivate input[name=txtUrl]").keyup(function(){
											actionChoise='&actionChoise=fill';
											h.submit();
											return true;
										});
				skineditorObj.addUrlDropdownEvent();
										
	//=================== set up object for edit form ======================================================================================
				var i = skineditor("#frmEdit form");
				i.submit(function(){
							skineditorObj.ajaxEditFile(this);
							return false;
						});	
				skineditor("#btEditText").click(function(){	
											actionChoise='&actionChoise=editfile';				
											//==== validate the controls ========================================================
											if(!getCheckedValue(skineditor("#formEdit input[name=optFiles]"))){
												document.getElementById("error_message").innerHTML="<div style=\'color: #111111\' class=\'error\'>Please select a file type option</div>"
												return true;
											}else{
												document.getElementById("error_message").innerHTML="";
												document.getElementById("txtcontent").innerHTML="";
											}
											//===============================================================================
											i.submit();
											return true;
										});
				skineditor("#btSaveText").click(function(){	
											actionChoise='&actionChoise=savefile';											
											//==== validate the controls ========================================================
											mypath = document.getElementById('info_message_edit').innerHTML;
											if (mypath.length<4){
												document.getElementById("error_message").innerHTML="<div style=\'color: #111111\' class=\'error\'>wrong path</div>"
												return true;
											}
											//===============================================================================
											mypath ='&mypath='+mypath;											
											i.submit();
											return true;
										});
				skineditor("#formEdit input[name=optFiles]").click(function(){	
											//actionChoise='&actionChoise=savefile';											
											//==== validate the controls ========================================================
											if(!validate(skineditor)){												
												
												return true;
											}else{
												if(getCheckedValue(skineditor("#formEdit input[name=csslevel]"))=='variation'){
													skineditor("#formEdit input[name=optFiles]")[0].checked = true;
												}
												document.getElementById("error_message").innerHTML="";
											}
											//===============================================================================											
											return true;
										});
				skineditor("#formEdit input[name=csslevel]").click(function(){	
											//actionChoise='&actionChoise=savefile';											
											validate(skineditor);
											return true;
										});
				skineditor("#formEdit input[name=txtUrlEdit]").keydown(function(){
											actionChoise='&actionChoise=filldomain';
											i.submit();
											return true;
										});
				skineditor("#formEdit input[name=txtUrlEdit]").keyup(function(){
											actionChoise='&actionChoise=filldomain';
											i.submit();
											return true;
										});
				skineditor("#formEdit select[name=ddlUrlEdit]").change(function(){
											actionChoise='&actionChoise=clear';
											i.submit();											
											return true;
										});
				skineditor("#formEdit select[name=ddlSTEdit]").change(function(){
											actionChoise='&actionChoise=fillvariationedit';
											i.submit();											
											return true;
										});
	//================================================================================================================================
				return;				
			},
			ajaxRunPage : function(val){					
					var data='';
					skineditor.ajax({							
							url: val,
							type: 'GET',
							data: data,
							//dataType: 'html',
							success:function(result, status, XMLHttpRequest){
										document.getElementById("info_message").innerHTML="<img src='images/loading.gif' align='middle'/><b>&nbsp;activating skin... </b>"										
										skineditorObj.ajaxActivateSubtheme();
										return false;
									},
							error:function(x,e){
										if(x.status==0){
										alert('You are offline!!\n Please Check Your Network.');
										}else if(x.status==404){
										alert('Requested URL not found.');
										}else if(x.status==500){
										alert('Internel Server Error.');
										}else if(e=='parsererror'){
										alert('Error.\nParsing JSON Request failed.');
										}else if(e=='timeout'){
										alert('Request Time out.');
										}else {
										alert('Unknow Error.\n'+x.responseText);
										}
										return false;
									}								
					});
			},
			ajaxActivateSubtheme : function(){					
					var data='';
					skineditor.ajax({							
							url: "/wp-admin/admin-ajax.php?action=skineditor_loopActivateTheme",
							type: 'GET',
							data: data,
							//dataType: 'html',
							success:function(result, status, XMLHttpRequest){
										document.getElementById("info_message").innerHTML="skin created and activated"
										return false;
									},
							error:function(x,e){
										if(x.status==0){
										alert('You are offline!!\n Please Check Your Network.');
										}else if(x.status==404){
										alert('Requested URL not found.');
										}else if(x.status==500){
										alert('Internel Server Error.');
										}else if(e=='parsererror'){
										alert('Error.\nParsing JSON Request failed.');
										}else if(e=='timeout'){
										alert('Request Time out.');
										}else {
										alert('Unknow Error.\n'+x.responseText);
										}
										return false;
									}								
					});
			},
			ajaxSaveFile : function(f){						
					f=skineditor(f);					
					var data=f.serialize();
						data+=actionChoise;
						data+=domainName;
						data+=hddlSTAct;
					skineditor.ajax({
							url: "/wp-admin/admin-ajax.php",
							type: 'GET',
							data: data,
							dataType: 'script',
							success:function(result, status, XMLHttpRequest){
										var s=skineditor("#info_message");
										var r=result.replace(/&#8203;/gi,'');										
										if(r.search(/document.getElementById/i)==-1){
											//s.html("");
											document.getElementById("info_message").innerHTML="<div style=\'color: #111111\' class=\'error\'>action failed</div>"
											return false;
										}
										s.show();
										if(actionChoise == '&actionChoise=fillAct'){											
											skineditorObj.setDdlVAct();
										}
										if(actionChoise == '&actionChoise=addSubTheme'){
											skineditorObj.ajaxRunPage("/wp-admin/ms-themes.php");											
											//set events
											skineditorObj.setDdlSTEditEvent();
											if(!skineditorObj.flagAddVariationDropdownEventDone){
												skineditorObj.addVariationDropdownEvent();
												skineditorObj.flagAddVariationDropdownEventDone = true;
											}
										}
										if(actionChoise == '&actionChoise=addVariation'){
											skineditorObj.setDdlVAct();
										}
										if(actionChoise == '&actionChoise=fill'){											
											skineditorObj.addUrlDropdownEvent();
										}
										return false;
									},
							error:function(x,e){
										if(x.status==0){
										alert('You are offline!!\n Please Check Your Network.');
										}else if(x.status==404){
										alert('Requested URL not found.');
										}else if(x.status==500){
										alert('Internel Server Error.');
										}else if(e=='parsererror'){
										alert('Error.\nParsing JSON Request failed.');
										}else if(e=='timeout'){
										alert('Request Time out.');
										}else {
										alert('Unknow Error.\n'+x.responseText);
										}
										return false;
									}								
					});
			},
			ajaxEditFile : function(frm){						
					frm=skineditor(frm);
					var data=frm.serialize();
						data+=actionChoise;
						data+=mypath;
					// skineditor.ajaxSetup({	
					// });
					skineditor.ajax({	
							url: "/wp-admin/admin-ajax.php",
							type: 'GET',
							data: data,
							dataType: 'script',
							success:function(result, status, XMLHttpRequest){
										var s=skineditor("#info_message_edit");
										var r=result.replace(/&#8203;/gi,'');
										if(r.search(/document.getElementById/i)==-1){
											document.getElementById("info_message").innerHTML="<div style=\'color: #111111\' class=\'error\'>action failed</div>"
										}
										s.show();										
										if(actionChoise == '&actionChoise=filldomain'){											
											skineditorObj.setddlUrlEdit();
										}
										return false;
									},
							error:function(x,e){
									if(x.status==0){
									alert('You are offline!!\n Please Check Your Network.');
									}else if(x.status==404){
									alert('Requested URL not found.');
									}else if(x.status==500){
									alert('Internel Server Error.');
									}else if(e=='parsererror'){
									alert('Error.\nParsing JSON Request failed.');
									}else if(e=='timeout'){
									alert('Request Time out.');
									}else {
									alert('Unknow Error.\n'+x.responseText);
									}
									return false;
								}							
					});
			},
			setDdlSTEditEvent : function(){
				var i = skineditor("#frmEdit form");				
				skineditor("#formActivate select[name=ddlSTEdit]").change(function(){
											actionChoise='&actionChoise=fillvariationedit';
											i.submit();
											return true;
										})
			},
			setDdlVAct : function(){
				var h = skineditor("#frmActivate form");
				skineditor("#formActivate select[name=ddlVAct]").change(function(){
											actionChoise='&actionChoise=createUrl';
											h.submit();
											return true;
										});
			},
			setddlUrlEdit : function(){
				var i = skineditor("#frmEdit form");
				skineditor("#formEdit select[name=ddlUrlEdit]").change(function(){
											actionChoise='&actionChoise=clear';
											i.submit();											
											return true;
										});
			},
			addVariationDropdownEvent : function(){
				var g = skineditor("#frmAddVariation form");
				var h = skineditor("#frmActivate form");
                                skineditor("#frmAddVariation select[name=ddlSubThemes]").change(function(){
											actionChoise='&actionChoise=fill';
											g.submit();
											return true;
										});
                                 skineditor("#formActivate select[name=ddlSTAct]").change(function(){
											actionChoise='&actionChoise=fillAct';
											h.submit();
											return true;
										});
			},
			addUrlDropdownEvent : function(){
				var h = skineditor("#frmActivate form");
				skineditor("#formActivate select[name=ddlUrl]").change(function(){								
							domainName='&domainName='+getSelectedName(document.getElementById("ddlUrl"));
							actionChoise='&actionChoise=createUrl';
							document.getElementById("btActivate").style.display = "none";
							h.submit();
							return true;
						});
			}
		};
		
		skineditor(document).ready(function(){
			skineditorObj.init()
		})
	}
)(jQuery);