window._tab = "    ";

function checkTab(evt) {
	var t = evt.target;
	var ss = t.selectionStart;
	var se = t.selectionEnd;
	// Set desired tab- defaults to four space softtab
	
	// Tab key - insert tab expansion
	if (evt.keyCode == 9) {
		evt.preventDefault();
		
		// Special case of multi line selection
		if (ss != se && t.value.slice(ss,se).indexOf("\n") != -1){
			// In case selection was not of entire lines (e.g. selection begins in the middle of a line)
			// we ought to tab at the beginning as well as at the start of every following line.
			var pre = t.value.slice(0,ss);
			var sel = t.value.slice(ss,se).replace(/\n/g,"\n"+_tab);
			var post = t.value.slice(se,t.value.length);
			t.value = pre.concat(_tab).concat(sel).concat(post);
			
			t.selectionStart = ss + _tab.length;
			t.selectionEnd = se + _tab.length;
		}
		else{// "Normal" case (no selection or selection on one line only)
			t.value = t.value.slice(0,ss).concat(_tab).concat(t.value.slice(ss,t.value.length));
			if (ss == se) {
				t.selectionStart = t.selectionEnd = ss + _tab.length;
			}
			else {
				t.selectionStart = ss + _tab.length;
				t.selectionEnd = se + _tab.length;
			}
		}
	}
	else if (evt.keyCode==8 && t.value.slice(ss - _tab.length,ss) == _tab) {// Backspace key - delete preceding tab expansion, if exists
		evt.preventDefault();
		
		t.value = t.value.slice(0,ss - _tab.length).concat(t.value.slice(ss,t.value.length));
		t.selectionStart = t.selectionEnd = ss - _tab.length;
	}
	else if (evt.keyCode==46 && t.value.slice(se,se + _tab.length) == _tab){// Delete key - delete following tab expansion, if exists
		evt.preventDefault();
		
		t.value = t.value.slice(0,ss).concat(t.value.slice(ss + _tab.length,t.value.length));
		t.selectionStart = t.selectionEnd = ss;
	}
	else if (evt.keyCode == 37 && t.value.slice(ss - _tab.length,ss) == _tab){// Left/right arrow keys - move across the tab in one go
		evt.preventDefault();
		t.selectionStart = t.selectionEnd = ss - _tab.length;
	}
	else if (evt.keyCode == 39 && t.value.slice(ss,ss + _tab.length) == _tab) {
		evt.preventDefault();
		t.selectionStart = t.selectionEnd = ss + _tab.length;
	}
}

RD.Podcast.Form = function(){
	if(!RD.Podcast.Form.Manager){
		RD.Podcast.Form.Manager = this;
	}

	return RD.Podcast.Form.Manager;
}

RD.Podcast.Form.prototype = new RD.XHTML.EventHandler();
RD.Podcast.Form.prototype.constructor = RD.Podcast.Form;
RD.Podcast.Form.superclass = RD.XHTML.EventHandler.prototype;

RD.Podcast.Form.Manager = null;
RD.Podcast.Form.getManager = function(){
	return new RD.Podcast.Form();
}

RD.Podcast.Form.prototype.init = function(){
	this.selectedFormat = null;
	this._exportingXML = false;
	this._importingXML = false;
	this._importFileName = String.empty;
	this._currentStep = 1;
	this._totalSteps = 1;
	this._completedStep = 0;
	this._divStepsLeft = 0;
	this._podcastJsHash = null;
	this._xmlCharacterEntities = [];
	this._formIsValid = true;
	this._currentPodcast = null;
	this._overlayAnimation = null;
	
	initWindowDimensions();

	this.bindPodcastJsHash();

	this.loadFormatClass();
};

RD.Podcast.Form.prototype.loadFormatClass = function(){
	if(isNull(eval(this.selectedFormat.classname))){
		this.setContentLoading(true);
		new RD.XHTML.XMLHttpLoadScript(RD.Podcast.Config.CODE_PATH + this.selectedFormat.filename + "?" + RD.XHTML.getUniqueId(), this, "loadFormatClass_Callback", null, null, false);
	}
	else{
		this.loadFormatClass_Callback({success:true});
	}
};

RD.Podcast.Form.prototype.loadFormatClass_Callback = function(aStatus){
	if(aStatus.success){
		var vDivSteps = $("divSteps");
	
		var vOldPodcast = this._currentPodcast;
		if(!isNull(vOldPodcast)){
			this._completedStep = 0;
			this._currentStep = 1;
			this._podcastJsHash.currentStep = 1;
			
			vOldPodcast.clearSteps(vDivSteps);
		}
		
		var vGuId = this._podcastJsHash.podcastGuId ? this._podcastJsHash.podcastGuId : String.empty;
		//alert(vGuId);
		this._currentPodcast = eval("new " + this.selectedFormat.classname + "();");

		this._currentPodcast.renderSteps(vDivSteps);
		
		this._totalSteps = this._currentPodcast._totalSteps;

		if(isNull(vOldPodcast)){
			if(vGuId.length > 0){
				this._currentPodcast.loadFromGuiId(vGuId, this, "loadFromGuiId_Callback");
			}
			else{
				this.loadFromGuiId_Callback();
			}
		}

		//each of the div steps have a width of 430px
		var vDivStepWidth = 430;
		
		vDivSteps.style.width = (this._totalSteps * vDivStepWidth) + "px";
		
		this._currentPodcast.setTabIndex(this._currentStep);

		RD.XHTML.initInputHighlight();
		RD.XHTML.infoRollover.getManager().init();
		RD.XHTML.setTextareaMaxLength();

		if(!isNull(vOldPodcast)){
			if(vOldPodcast.getFormat() == RD.Podcast.Config.FORMATS.STANDARD){
				this._currentPodcast.copyStandardToPodcast(vOldPodcast);
			}
			else{
				vOldPodcast.copyPodcastToStandard(this._currentPodcast);
			}

			this.loadFromGuiId_Callback();
		}

		this.getXmlCharacterEntities();
	}
};

RD.Podcast.Form.prototype.getXmlCharacterEntities = function(){
	if(this._xmlCharacterEntities.length == 0){
		this.setContentLoading(true);
		RD.XHTML.XMLHttpRequestHandler("data/xmlCharacterEntities.dat", "GET", this, "getXmlCharacterEntities_Callback", null, null, true);
	}
};

RD.Podcast.Form.prototype.getXmlCharacterEntities_Callback = function(aStatus){
	if(aStatus.success){
		var vCharEntities = aStatus.responseText.split("\n");
		var vCharEntity;
		for(var n=0;n<vCharEntities.length;n++){
			vCharEntity = vCharEntities[n].split("\t");
			if(vCharEntity[0].trim()){
				this._xmlCharacterEntities.push({character:vCharEntity[0].trim(), entity:vCharEntity[1].trim()});
			}
		}
	}
	this.setContentLoading(false);
};

RD.Podcast.Form.prototype.bindStepsSelection = function(){
	var vStepsSelector = $("stepsSelector");
	//first thing we will do is remove any existing step selector nodes
	var vAnchorNodes = $$(vStepsSelector, "a");
	var vLength = vAnchorNodes.length;
	
	for(var n=0;n<vAnchorNodes.length;n++){
		if(n < this._totalSteps){
			if(n > 0){
				vAnchorNodes[n].className = "form-btn-disabled";
			}
		}
		else{
			vStepsSelector.removeChild(vAnchorNodes[n]);
			vLength--;
		}
	}

	//now loop through and add any selectors nodes still needed
	for(var n=vLength;n<this._totalSteps;n++){
		var vANode = RD.XHTML.NodeHelper.createNode("a", vStepsSelector, {
				href:"javascript://"
				,className:"form-btn-disabled"
			}
			,(n+1).toString()
		);
		
		vANode.setAttribute("stepNumber", n+1);
		vANode.onclick = function(evt){
			var vFormManager = RD.Podcast.Form.getManager();
			var vNewStep = parseInt(this.getAttribute("stepNumber"), 10);

			if(vNewStep > vFormManager._currentStep){
				for(var n=vFormManager._currentStep;n<vNewStep;n++){
					vFormManager._currentPodcast.initNextStep(n);
					vFormManager.validate(n);

					if(!vFormManager._formIsValid){
						vNewStep = n;
						break;
					}
				}
			}
			else if(vNewStep >= 1 && vNewStep < vFormManager._currentStep){
				vFormManager._currentPodcast.initPreviousStep(vNewStep);
				/*
				for(var n=vFormManager._currentStep;n>vNewStep;n--){
					vFormManager._currentPodcast.initPreviousStep(n);
					vFormManager.validate(n);
					if(!vFormManager._formIsValid){
						vNewStep = n;
						break;
					}
				}
				*/
			}

			var vShowStep = vFormManager.showStep(evt, vNewStep);

			if(vShowStep){
				vFormManager.setContentLoading(true);
				RD.XHTML.XMLHttpRequestHandler("php_scripts/rd_podcasthelper.php?fn=setCurrentStep&fa=" + vFormManager._currentStep + "&" +  (new Date().getTime()), "GET", RD.Podcast.Form.getManager(), "bindStepsSelection_Callback", null, null, true);
			}
		};

		if(n == 0){
			vANode.className = "form-btn-hover";
		}
	}
};

RD.Podcast.Form.prototype.bindStepsSelection_Callback = function(aStatus){
	this.setContentLoading(false);
};

RD.Podcast.Form.prototype.setContentLoading = function(aIsContentLoading){
	var vDivOverlay = $("divOverlayTransparent");
	var vWait = $("divWait_ContentLoad");
	if(aIsContentLoading){
		vDivOverlay.style.zIndex = 9998;
		vWait.style.display = "block";
	}
	else{
		vDivOverlay.style.zIndex = -1;
		vWait.style.display = "none";
	}
};

RD.Podcast.Form.prototype.bindPodcastJsHash = function(){
	if(isNull(this._podcastJsHash)){
		this.setContentLoading(true);
		
		RD.XHTML.XMLHttpRequestHandler("php_scripts/rd_podcasthelper.php?fn=getPodcastJsHash" + "&" +  (new Date().getTime()), "GET", this, "bindPodcastJsHash_Callback", null, null, false);
	}
};

RD.Podcast.Form.prototype.bindPodcastJsHash_Callback = function(aStatus){
	if(!aStatus.success){
		alert(aStatus.responseText);
	}
	else{
		this._podcastJsHash = aStatus.responseText.trim().toObject();
		
		if(!isNull(this._podcastJsHash.format)){
			this.selectedFormat = RD.Podcast.Config.formats[this._podcastJsHash.format];
		}
		
		if(!isNull(this._podcastJsHash.podcastGuId)){
			this._completedStep = this._podcastJsHash.completedStep;
		}
		else{
			var vOverlay = $("divOverlayOpaque");
			vOverlay.style.display = "none";
		
			var vWait = $("imgWait_SiteLoad");
			vWait.style.display = "none";
		}
	}
	
	this.setContentLoading(false);
};

RD.Podcast.Form.prototype.loadFromGuiId_Callback = function(aStatus){
	if(!isNull(aStatus) && !aStatus.success){
		this._completedStep = 0;
		this._currentStep = 1;
		this._podcastJsHash.currentStep = 1;
	}
	
	this.bindStepsSelection();
	
	this.bindForm();

	this.showStep(null, this._podcastJsHash.currentStep, true);
	
	if(this._podcastJsHash.currentStep == 1){
		this._currentPodcast.setFocusToFirstInput(this._podcastJsHash.currentStep);
	}
};

RD.Podcast.Form.prototype.bindForm = function(){
	this._currentPodcast.bindForm();

	var vOverlay = $("divOverlayOpaque");
	vOverlay.style.display = "none";

	var vWait = $("imgWait_SiteLoad");
	vWait.style.display = "none";
};

RD.Podcast.Form.prototype.toggleSiblingNode = function(vNode, vStartDisplay){
	var vSibling = vNode.nextSibling;
	var vDisplay = null;
	while( vSibling != null){
		if(vSibling.nodeName != "#text"){
			vDisplay = vSibling.style.display;
			vSibling.style.display = (vDisplay == "none")?vStartDisplay:"none";
			break;
		}
		vSibling = vSibling.nextSibling;
	}
};

RD.Podcast.Form.prototype.toggleEpisodes = function(evt){
	this._currentPodcast.toggleEpisodes(evt);
};

RD.Podcast.Form.prototype.previousStep = function(evt){
	evt = evt?evt:window.event;
	var vTarget = evt.target ? evt.target : evt.srcElement;

	var vCurrentStep = this._currentStep;
	if(!vCurrentStep){
		vCurrentStep = 1;
	}

	if(vCurrentStep > 1){

		vCurrentStep--;

		this._currentPodcast.initPreviousStep(this._currentStep);

		//this.validate(this._currentStep);

		if(this._formIsValid){
			if(vCurrentStep < this._totalSteps){
				var vShowStep = this.showStep(evt, vCurrentStep);
				/*
				if(vShowStep){
					this.update(vCurrentStep+1, false);
				}
				*/
			}
		}
	}
};

RD.Podcast.Form.prototype.nextStep = function(evt){
	evt = evt?evt:window.event;
	var vTarget = evt.target ? evt.target : evt.srcElement;

	if(vTarget.className.indexOf("disabled") < 0){
		var vCurrentStep = this._currentStep;
		if(!vCurrentStep){
			vCurrentStep = 1;
		}

		this._currentPodcast.initNextStep(this._currentStep);

		this.validate(this._currentStep);

		if(this._formIsValid){
			if(vCurrentStep < this._totalSteps){
				var vShowStep = this.showStep(evt, vCurrentStep+1);
				
				if(vShowStep){
					this.update(vCurrentStep, true);
				}
			}
		}
	}
};

RD.Podcast.Form.prototype.showStep = function(evt, aStep, aRefreshSelectors){
	aRefreshSelectors = (aRefreshSelectors != null)?aRefreshSelectors:false;
	var vShowStep = false;

	if(aStep != this._currentStep){
		evt = evt?evt:window.event;
		var vTarget = null;
		if(evt){
			vTarget = evt.target ? evt.target : evt.srcElement;
		}

		if(!vTarget || vTarget.className.indexOf("disabled") < 0){
			aStep = (aStep != null && aStep > 0 && aStep <= this._totalSteps)?aStep:1;
			
			this._currentPodcast.showStep(aStep, this._totalSteps);

			var vDir = (aStep > this._currentStep)?-1:1;
			var vStepChangeAmt = -vDir * (aStep - this._currentStep);
			var vLeftChangeAmount = 40 * vDir * vStepChangeAmt;
			
			this._divStepsLeft += 430 * vDir * vStepChangeAmt;
		
			var vDivSteps = $("divSteps");
			var vAnimate = new RD.XHTML.Animation({
				changeNode:vDivSteps
				,changeStyleProperty:["left"]
				,intervalAmount:33
				,changeAmount:[vLeftChangeAmount]
				,startValue:[(this._divStepsLeft - (430 * vDir * vStepChangeAmt))]
				,endValue:[this._divStepsLeft]
				,startTime:0
				,fill:"freeze"
				,callback:this.onAnimate
			});
			vAnimate.start();

			vAnimate = new RD.XHTML.Animation({
				changeNode:"divStep_" + this._currentStep
				,changeStyleProperty:["opacity"]
				,intervalAmount:33
				,changeAmount:[vLeftChangeAmount * 0.2]
				,startValue:[100]
				,endValue:[0]
				,startTime:0
				//,fill:"freeze"
			});
			vAnimate.start();

			this._currentStep = aStep;

			vAnimate = new RD.XHTML.Animation({
				changeNode:"divStep_" + this._currentStep
				,changeStyleProperty:["opacity"]
				,intervalAmount:33
				,changeAmount:[vLeftChangeAmount * 0.2]
				,startValue:[0]
				,endValue:[100]
				,startTime:0
				,fill:"freeze"
				,callback:this.onAnimate
			});
			vAnimate.start();
			
			vShowStep = true;
		}
	}
	
	if(aRefreshSelectors || vShowStep){
		var vSelectorNodes = $$($("stepsSelector"), "a");
		for(var n=0;n<this._totalSteps;n++){
			if(n == this._currentStep-1){
				vSelectorNodes.item(n).className = "form-btn-hover";
			}
			else if(vSelectorNodes.item(n).className.indexOf("disabled") < 0 || n <= this._completedStep){
				vSelectorNodes.item(n).className = "form-btn";
			}
		}
	}
	
	this._currentPodcast.setTabIndex(this._currentStep);
	
	return vShowStep;
};

RD.Podcast.Form.prototype.update = function(aCurrentStep, aShowNext){
	aShowNext = (aShowNext != null)?aShowNext:false;

	if(aShowNext && aCurrentStep > this._completedStep){
		this._completedStep = aCurrentStep;
	}

	this._currentPodcast.update(aCurrentStep, null);

	this.setContentLoading(true);
	RD.XHTML.XMLHttpRequestHandler("php_scripts/rd_podcasthelper.php?fn=updatePodcast&pguid=" + this._currentPodcast._guid + "&pcrs=" + this._currentStep + "&pcms=" + this._completedStep + "&pfor=" + this._currentPodcast.getFormat() + "&" +  (new Date().getTime()), "GET", this, "update_Callback", null, null, true);
};

RD.Podcast.Form.prototype.update_Callback = function(aStatus){
	this.setContentLoading(false);
};

RD.Podcast.Form.prototype.setFormat = function(evt){
	this._currentPodcast.setFormat(null, evt);
};

RD.Podcast.Form.prototype.selectEpisode = function(evt, aTarget){
	evt = evt?evt:window.event;
	var vTarget = null;
	if(evt){
		vTarget = evt.target ? evt.target : evt.srcElement;
	}
	else if(aTarget){
		vTarget = aTarget;
	}

	if(vTarget){
		this._currentPodcast.selectEpisode(vTarget, aTarget);
	}
};

RD.Podcast.Form.prototype.shiftEpisode = function(evt){
	evt = evt?evt:window.event;
	var vTarget = null;
	if(evt){
		vTarget = evt.target ? evt.target : evt.srcElement;
	}

	if(vTarget && vTarget.className.indexOf("disabled") < 0){
		this._currentPodcast.shiftEpisode(vTarget);
	}
};

RD.Podcast.Form.prototype.addEpisode = function(evt){
	evt = evt?evt:window.event;
	var vTarget = null;
	if(evt){
		vTarget = evt.target ? evt.target : evt.srcElement;
	}

	if(vTarget.className.indexOf("disabled") < 0){
		this._currentPodcast.initValidate();

		this.validate(this._currentStep);
		
		if(this._formIsValid){
			var vEpisode = this._currentPodcast.addEpisode();
			if(vEpisode){
				this.update();
			}
		}
	}
	//this.nextStep(evt);
};

RD.Podcast.Form.prototype.deleteEpisode = function(evt){
	evt = evt?evt:window.event;
	var vTarget = null;
	if(evt){
		vTarget = evt.target ? evt.target : evt.srcElement;
	}
	
	if(vTarget.className.indexOf("disabled") < 0){
		this._currentPodcast.deleteEpisode();
	}
};

RD.Podcast.Form.prototype.saveEpisode = function(evt){
	evt = evt?evt:window.event;
	  var vTarget = null;
	  if(evt){
		vTarget = evt.target ? evt.target : evt.srcElement;
	  }
			
	  this.validate(this._currentStep);
	  
	  if(this._formIsValid){
		var vDivSteps = $("divStep_4_Container");
	  
		var vAnimate = new RD.XHTML.Animation({
		  changeNode:vDivSteps
		  ,changeStyleProperty:["top"]
		  ,intervalAmount:33
		  ,changeAmount:[40]
		  ,startValue:[-260]
		  ,endValue:[0]
		  ,startTime:0
		  ,fill:"freeze"
		});
		vAnimate.start();
	  }
};

RD.Podcast.Form.prototype.validate = function(aCurrentStep){
	this._formIsValid = true;
	var vDivStep =  $("divStep_" + aCurrentStep);

	if(vDivStep){
		var vChildDivs = $$(vDivStep, "div");
		var vChildDiv = null;
		var vInput = null;
		var vValidationType = null;

		for(var n=0;n<vChildDivs.length;n++){
			vChildDiv = vChildDivs.item(n);
			vValidationType = vChildDiv.getAttribute("validationType");
			if(vValidationType){
				if(vChildDiv.getAttribute("isEnabled") != "disabled"){
					vChildDiv.className = vChildDiv.className.replace("visible", "hidden");
					switch(vValidationType){
						case "required":
							vInput = $(vChildDiv.getAttribute("inputId"));
							if(vInput){
								switch(vInput.nodeName.toLowerCase()){
									case "input":
									case "textarea":
									case "select":
										if(vInput.value.trim().length == 0 || vInput.value.trim() == vChildDiv.getAttribute("defaultValue")){
											this._formIsValid = false;
											vChildDiv.className = vChildDiv.className.replace("hidden", "visible");
										}
										break;
									case "div":
										var vEpisodes = this._currentPodcast.getEpisodes();

										if(vInput.id == "divEpisodes" && !vEpisodes.length){
											this._formIsValid = false;
											vChildDiv.className = vChildDiv.className.replace("hidden", "visible");
										}
										break;
								}
							}
							break;
						case "regex":
							var vValidate = vChildDiv.getAttribute("validation");
							
							vInput = $(vChildDiv.getAttribute("inputId"));
							if(vInput){
								
								switch(vInput.nodeName.toLowerCase()){
									case "input":
									case "textarea":
									case "select":
										var vValue = vInput.value.trim();
										if(vValue){
											var vRegExp = new RegExp(vValidate, "g");
											if(!vRegExp.test(vValue)){
												this._formIsValid = false;
												vChildDiv.className = vChildDiv.className.replace("hidden", "visible");
											}
										}
										break;
								}
							}
						default:
							break;
					}
				}
				else{
					vChildDiv.className = vChildDiv.className.replace("visible", "hidden");
				}
			}
		}
	}
};

RD.Podcast.Form.prototype.onAnimate = function(aAnimate){
	//IE 7 can handle transparent pngs...but not if used in conjunction
	//with the opacity filter
	if(aAnimate._status == RD.XHTML.Animation.STATUS.OFF){
		if(RD.XHTML.initPngFix && aAnimate._changeStyleProperty[0] == "opacity"){
			RD.XHTML.initPngFix();
		}
		else if(aAnimate._changeStyleProperty[0] == "left"){
			var vFormManager = RD.Podcast.Form.getManager();
			//alert(vFormManager._currentStep);
			vFormManager._currentPodcast.setFocusToFirstInput(vFormManager._currentStep);
		}
	}
};

RD.Podcast.Form.prototype.publish = function(){
	this._currentPodcast.publish();
};

RD.Podcast.Form.prototype.publish_Callback = function(){
	var vOverlay = $("divOverlayOpaque");
	vOverlay.style.display = "none";

	var vWait = $("divWait");
	vWait.style.display = "none";

	this._exportingXML = false;
	window.location = "php_scripts/rd_io_export_file.php?export=1&filename=" + this._xmlFileName;
};