// Function clears form or form elements [usage: element.clearForm()]

$.fn.clearForm = function(){
return this.each(function() {
 var type = this.type, tag = this.tagName.toLowerCase();
 if (tag == 'form')
   return $(':input',this).clearForm();
 if (type == 'text' || type == 'password' || tag == 'textarea')
   this.value = '';
 else if (type == 'checkbox' || type == 'radio')
   this.checked = false;
 else if (tag == 'select')
   this.selectedIndex = 0;
  });
};

// Include Scenario Plugin.

$(document).ready(function(){

	var startPath = "http://www.netromedia.com/StartNow/tabid/609/Default.aspx";

	$("#viewerDuration, #bitrate, #dailyViewers").bind("change", function(){

		var d = 365/12;
		var v = $("select[name='dailyViewers']").val();
		var b = $("select[name='bandBitrate']").val();
		var m = $("select[name='viewerDuration']").val();

		if (!isNaN(d*1) && !isNaN(m*1) && !isNaN(v*1) && !isNaN(b*1))
		{
			var bandwidth = updateBandwidth(d,m,v,b);
			$(".GBresult #noCalcYet").hide();
		}
		else
		{
			return false;
		}
	});

	function calcGB(m,v,b)
	{
		var result = (b*m)*v*30;
		result = (result * 10) / 1024;

		// Less than 1 GB, More than 0
		if (result > 0 && result < 1)
		{
			result = 1;
		}

		// More than 1 GB
		else
		{
			result = Math.round(result);
		}

		return result;
	}
	
	function formatTranslator(formatCode)
	{
		switch(formatCode)
		{
			case "wm": return "Windows Media";
			break;

			case "qt": return "Quicktime";
			break;

			case "flv": return "Flash";
			break;

			case "st9": return "Shoutcast";
			break;

			case "na": return "";
			break;
		}
	}

	/* --
	Fucntion gets, and returns an array with three values: subStep - the next step in the process (moveTo#),
	innerSubStep - an inner sub-category [if found], formatMatched - a boolean with value 1 if the current category was found in the step condition.
	-- */

	function condNextStep(subStep, stepCat)
	{
		var condArray = Array();
		var innerSubStep;
		var formatMatched = 0; // Added: 16/09/09

		var catListArray = subStep.split(",");

		jQuery.each(catListArray, function() {
			var moreSplit = this.split(":");

			// If step category matches next step condition prefix, select next step.
			if (moreSplit[0] == stepCat)
			{

				subStep = moreSplit[1];

				// Get sub-category (inner category) of next step.
				if (moreSplit[1].indexOf("_") != -1)
				{
					var moreSplit2=moreSplit[1].split("_");
					subStep = moreSplit2[0];
					innerSubStep = moreSplit2[1];
				}

				formatMatched = 1;

			}
		});

		condArray['subStep'] = subStep;
		condArray['innerSubStep'] = innerSubStep;
		condArray['formatMatched'] = formatMatched;

		return condArray;
	}

	// Hide all div's in serviceSelector, except the first one.
	$("#serviceSelector > div:not(:first-child)").hide();

	// toggleSlide step when title link is clicked.
	$("a.stepTitle").click(function(){
		var targetCont = $(this).attr("rel");
		var subTargetCont = $(this).attr("rev");
		var mainClass = ".main";

		// If sub-category specified, toggle only sub-category main & title.
		if (subTargetCont.length > 0)
		{
			mainClass = mainClass+"."+subTargetCont;
		}

		$("#"+targetCont+" "+mainClass+"").slideToggle(600);
		return false;
	});

	function moveToNextStep()
	{
		// Define moveTo flag
		var moveToFlag = false;

		// Get name of radio button pressed, in the form of "step#"
		var stepFullID = $(this).attr("name");

		// If a certain radio button has an ID set, show the next step based on that ID (in the format of step1). "moveTo#" is a command to skip to step #.
		var subStep = $(this).attr("id");

		// Set innerSubStep to store _SUBSTEPID in conditional statement.
		var innerSubStep;

		// Set conditional next step to 0, change to 1 when next step is based on a condition.
		var conditionalNextStep = 0;

		// Get ID out of step full ID (strip out "step" text).
		var stepNum = parseInt(stepFullID.replace("step", ""));

		// Store choice of Streaming Format (step1 only)
		if ($(this).attr("name") == "step1")
		{
			var stepCat = $(this).attr("value");

			// Hide all steps (other than first step) when changing step1
			$("#serviceSelector > div:not(:first-child)").hide();

			// Clear all inputs with previously set values after this step (when changing format).
			$("#"+stepFullID+"Cont").nextAll("div").find("input, select").clearForm();
		}

		// Store choice of checked streaming format from step1 (for all steps)
		else
		{
			var stepCat = $(".radioButtons input[type='radio'][name='step1']:checked").val();

			// Hide all next steps when changing step
			$("#"+stepFullID+"Cont").nextAll("div").hide();

			// Clear all inputs after this step (when changing previously set values.
			$("#"+stepFullID+"Cont").nextAll("div").find("input, select").clearForm();
		}

		// Define next step [Normal mode]: move to next step in order (no moveTo id specified on radio button)
		if (subStep.indexOf("moveTo") == -1)
		{
			var nextNum = stepNum + 1;
			var nextFullID = "step"+nextNum;
		}

		// Define next step [moveTo mode]: skip to certain step (moveTo ID specified on previous radio button)
		else
		{
			var formatMatched = 0;
			conditionalNextStep = 1;

			// Parse conditional Next Step.
			var condArray = condNextStep(subStep, stepCat);

			// Copy array values into global variables (for sake of readability)
			subStep = condArray['subStep'];
			innerSubStep = condArray['innerSubStep'];
			formatMatched = condArray['formatMatched'];

			// No match with conditional "moveTo", then use next step as "moveTo" category
			// Added: 16/09/09
			if (formatMatched == 0)
			{
				var temp = parseFloat(stepFullID.replace("step", "")) + 1;
				subStep = "moveTo"+temp;
			}

			var moveToFlag = true;
			var moveTo = subStep.replace("moveTo", "");
			var nextFullID = "step"+moveTo;
		}

		// Show next step in category (category specified by first step choice: wm, st, flv etc.). Do not show elements with "hide" class.
		$("#"+nextFullID+"Cont."+stepCat+" div:not(.hide)").show();

		// Determine step order dynamically, based on previous visible steps.
		var arr = jQuery.makeArray($("#"+stepFullID+"Cont").prevAll("div:not(:hidden)"));
		var stepOrder = arr.length+2;

		// Change title based on stepOrder
		$("#"+nextFullID+"Cont .title span.numStep").text(stepOrder);

		$("#"+nextFullID+"Cont."+stepCat+"").slideDown();

		// Hide current step content
		$("#"+stepFullID+"Cont .main").slideUp(600);

		// Option one: If subStep ID set: show only relevant main and title in next step based on previous radio button selection ID
		// Option two: condition has been carried out, and innerSubStep present.
		if (subStep.length > 0 && moveToFlag != true || conditionalNextStep == 1 && innerSubStep != null)
		{
			// If conditional next step has taken place, set "subStep" to "innerSubStep" *** Pay close attention to subStep variables that MAY appear here later.
			if (conditionalNextStep == 1)
			{
				subStep = innerSubStep;
			}

			// Hide all content and titles in step
			$("#"+nextFullID+"Cont .main, #"+nextFullID+"Cont .title").hide();

			// Show only relevant title and content, based on category
			$("#"+nextFullID+"Cont .main."+subStep+", #"+nextFullID+"Cont .title."+subStep+"").show();
		}

		// Get Label of selected streaming format [label must be immediate sibling of input].
		var label = $(this).next("label").text();

		// Change title based on selected input's label
		$("#"+stepFullID+"Cont .title span.choice").html("(<strong>"+label+"</strong>, or click here to change)");

		// Add selection to overview
		var overviewTitle = $("#"+stepFullID+"Cont .title a").attr("title");
		var divsInOverview = $("#overview #"+stepFullID).size();
		var newOverviewDiv = "<div id=\""+stepFullID+"\"><u>"+overviewTitle+""+"</u>: <strong>\""+label+"\"</strong>"+"</div>";

		// If overview item with that ID exists, replace changed option with previous option.
		if (divsInOverview == 1)
		{
			$("#overview #"+stepFullID).replaceWith(newOverviewDiv);
			$("#overview #"+stepFullID).nextAll("div").remove();
		}

		// If overview option does not exist, append chosen option.
		else
		{
			$("#overview").append(newOverviewDiv);
		}
	}

	// Move steps forward and backwards based on radio button selection.
	$(".radioButtons input[type='radio']").click(moveToNextStep); /* Changed from "focus" to "click" to support all browsers */

	// When form is submitted, handle values
	$("#concSubmit, #bandSubmit").click(function(){
		var valueArray = new Array();
		$("input:checked,select").each(function(){
			if ($(this).val() != null)
			{
				var name = $(this).attr("name");
				var val = $(this).val();

				valueArray[name] = val;
			}
		});

		var format = formatTranslator(valueArray["step1"]);
		var service = valueArray["step2"];
		var pricing = $(this).attr("id");

		// Change "I Don't Know" to "Default"
		if (service == "I Don't Know")
		{
			service = "Default";
		}

		if (pricing == "concSubmit")
		{
			// If concurrent prices set, and values given:
			if ($("select[name='concViewers']").val() != "pc" && $("select[name='concBitrate']").val() != "pc")
			{
				if ($("select[name='concViewers']").val() != "" && $("select[name='concBitrate']").val() != "")
				{
					var concViewers = $("select[name='concViewers']").val();
					var concBitrate = $("select[name='concBitrate']").val();
					var finalLink = startPath+"?mpi="+service+"&pid=765&forkmat="+format+"&viewers="+concViewers+"&bitrate="+concBitrate;

					//var finalGB = calcGB();
					window.location = finalLink;
				}
				else
				{
					alert("You must fill in all the fields in the form to create a service.\r\nIf you don't know - choose that option.");
				}
			}
			else
			{
				alert("You must fill in all the fields in the form to create a service.\r\nIf you don't know - choose that option.");
			}
		}

		if (pricing == "bandSubmit")
		{
			// If bandwidth prices set, and values given:
			if ($("select[name='dailyViewers']").val() != "pc" && $("select[name='viewerDuration']").val() != "pc" && $("select[name='bandBitrate']").val() != "pc")
			{
				if ($("select[name='dailyViewers']").val() != "" && $("select[name='viewerDuration']").val() != "" && $("select[name='bandBitrate']").val() != "")
				{
					var bandViewers = $("select[name='dailyViewers']").val();
					var bandBitrate = $("select[name='bandBitrate']").val();
					var bandDuration = $("select[name='viewerDuration']").val();

					//var finalGB = calcGB(bandDuration,bandViewers,bandBitrate);

					// Access calculator function.
					var finalGB = updateBandwidth(365/12, bandDuration, bandViewers, bandBitrate);

					if (finalGB == 0 || finalGB == null)
					{
						var finalLink = startPath+"?mpi="+service+"&pid=765&forkmat="+format+"&viewers="+bandViewers+"&bitrate="+bandBitrate+"&duration="+bandDuration;
					}
					else
					{
						var finalLink = startPath+"?mpi="+service+"&pid=765&forkmat="+format+"&band="+finalGB+"%20GB&viewers="+bandViewers+"&bitrate="+bandBitrate+"&duration="+bandDuration;
					}

					window.location = finalLink;
				}
				else
				{
					alert("You must fill in all the fields in the form to create a service.\r\nIf you don't know - choose that option.");
				}
			}
			else
			{
				alert("You must fill in all the fields in the form to create a service.\r\nIf you don't know - choose that option.");
			}
		}

		return false;
	});

	// Scenario handling. Auto-fill form.

	$("#scenarioList div a").click(function(){
		var stepList = $(this).attr("rel");
		var stepArray = stepList.split(",");

		jQuery.each(stepArray, function() {
			var stepCommands = this.split(":");
			var stepID = stepCommands[0];
			var stepValue = stepCommands[1];

			$("input[name='step"+stepID+"'][value='"+stepValue+"']").attr("checked", "true");
			$("input[name='step"+stepID+"'][value='"+stepValue+"']").trigger("click");
		});

		return false;
	});
	
	// General functions
	/* Toggle function */
	
	$(".toggleDiv").click(function(){
		var target = $(this).attr("href");
		$(target).toggle();

		return false;
	});
	
});