$(document).ready(function() {
	//Set up the Default State of the shop

	//Create the corners on the tabs and os containers
	//$("div[class ^='os-body']").corner("top 5px");
	//$("li[id ^='plan-type-tab_']").corner("top 5px");

	$("div[class = 'redirect-url']").each(function() {
		$(this).hide();
	});

	var already_selected = false;

	//Show the tab for the selected os type, the other tabs are set to opacity 0.6
	show_selected_tab();

	$("div[class ^='os-body']").each( function() {
		var plan_name = $(this).attr("name");
		var preselected_plan = $("input[id = 'preselected_plan']").val();

		if (plan_name == preselected_plan) {
			var os_id = get_os_id($(this));
			
			set_previous_period_choice(os_id);
			set_previous_plesk_added_choice(os_id);
			set_previous_plesk_licence_choice(os_id);

			assign_plesk_licence_price(os_id);
			//assign_periods_currency_symbol();
			//Animate the rest of the oss to the bottom of the container in rows
			animate_non_selected(os_id);
			expand_selected_os(os_id);
			already_selected = true;
			//check_or_uncheck_30_domains_licence(os_id);
		}	
	});

	//If a selected os already exists in the session cookie, expand that and compact 
	//the rest (handled by expand_selected_os()
	var prev_os_id = get_cookie("selected_os_id");
	if (prev_os_id && !already_selected) {
		set_previous_period_choice(prev_os_id);
		set_previous_plesk_added_choice(prev_os_id);
		set_previous_plesk_licence_choice(prev_os_id);

		assign_plesk_licence_price(prev_os_id);
		//assign_periods_currency_symbol();
		//Animate the rest of the oss to the bottom of the container in rows
		animate_non_selected(prev_os_id);
		expand_selected_os(prev_os_id);
	}

	var redirect_error = $("h3[id = 'redirect_error']");
	if (redirect_error) {
		var footer = $("div[id = 'footerhome']");
		footer.css("top", "170px");
	}

	//If a period option is selected, get the os of the expanded pane
	//and show plesk option is avail., and show the purchase option
	//if all necessary options for the selected os are chosen
	$("input[name='period']").live('click', function() {
		period_clicked($(this));
	});

	//If a plesk licence option is chosen, show the purchase option if necessary
	$("input[name='plesk-licence-id']").live('click', function() {
		licence_clicked($(this));	
	});

	//If the "What is Plesk" option is clicked, launch the help window
	$("span[id ^='windowOpen'], a[id ^='windowOpen']").live('click', function() {
		$("div[id='window']").animate({height:"30em", width:"33.5em", left: "200px", top: "300px" }, { duration: 500 });        
	});

	//Close the help window
	$("img[id='windowClose']").live('click', function() {
		$("div[id='window']").animate({height:"0em", width:"0em"}, { duration: 500 });       
	});

	//If a os container is selected, regardless of state, expand it 
	//(provided it is not already expanded)
	$("div[class ^='os-body']").live('click', function() {
		//Get the os_id of the os selected
		var os_id = $(this).attr('id');
		os_id = os_id.substring(os_id.indexOf("_") + 1, os_id.indexOf("_container"));

		//Find out if the os selected is already expanded
		if ($("#current-os_" + os_id).attr('value') == "no") {
			//Store the selected os id in a session cookie
			document.cookie = "selected_os_id=" + os_id;

			//Reset the session cookie option values 
			remove_cookie("selected_subscription_period");
			remove_cookie("selected_plesk_licence");
			remove_cookie("plesk_added");

			//Animate the rest of the oss to the left of the container
			expand_selected_os(os_id);
			animate_non_selected(os_id);
		}
	});

	//If the add plesk option is selected, show the plesk licence options,
	//and the purchase link if necessary
	$("input[id ^='plesk-added_']").live('click', function() {
		var os_id = $(this).attr('id').substring($(this).attr('id').indexOf('_') + 1);

		assign_plesk_licence_price(os_id);
		//assign_periods_currency_symbol();

		store_plesk_added_choice($(this))

		show_or_hide_plesk_unavailable_alert(os_id);
		show_or_hide_plesk(os_id);
		show_or_hide_purchase_link(os_id);
		show_or_hide_mgmt_option(os_id);
	});

});

function hide_button(os_id){
	var button = $("div[id='purchase_" + os_id + "']")
	button.hide();
}

function licence_clicked(element) {
	var os_id = get_os_id(element)

	store_plesk_licence_choice(os_id);
	var elem_id = element.attr("id");
	//swap_plesk_licence_choice(os_id, elem_id);
	show_or_hide_purchase_link(os_id);
}

function period_clicked(element) {
	var os_id = get_os_id(element);
	
	store_period_choice(os_id);
	assign_plesk_licence_price(os_id);
	//assign_periods_currency_symbol();
	show_or_hide_plesk_unavailable_alert(os_id);
	show_or_hide_plesk(os_id);
	show_or_hide_purchase_link(os_id);
	show_or_hide_mgmt_option(os_id);
}

// Get a boolean value for plesk availability based on a os id
function plesk_available(os_id) {
	var input_name = "plesk_available_" + os_id;
	var plesk_available = $("input[name = '" + input_name + "']").attr("value");
	if (plesk_available === "yes") {
		return true;
	}
	return false;
}

function mgmt_available(os_id) {
	var input_name = "mgmt_available_" + os_id;
	var plesk_available = $("input[name = '" + input_name + "']").attr("value");
	if (plesk_available === "yes") {
		return true;
	}
	return false;
}

function mgmt_plesk_available(os_id) {
	var input_name = "mgmt_plesk_available_" + os_id;
	var plesk_available = $("input[name = '" + input_name + "']").attr("value");
	if (plesk_available === "yes") {
		return true;
	}
	return false;
}

function plan_id_selected(os_id) {
	var padded = $("input[id ^='plesk-added_" + os_id + "']").is(":checked");
	if (padded) {
		return $("input[id = 'plesk-plan-id_" + os_id + "']").attr("value");
	} else {
		return $("input[id = 'plan-id_" + os_id + "']").attr("value");
	}
}

function period_id_selected(os_id) {
	var period_input = $("input[id ^= 'period_" + os_id + "']:checked");
	if (period_input.size() != 0) {
		var period_id = period_input.attr("value");
		return period_id;
	}
	return false;
}

function plesk_period_id_selected(os_id) {
	var period_input = $("input[id ^= 'period_" + os_id + "']:checked");
	var padded = $("input[id ^='plesk-added_" + os_id + "']").is(":checked");
	if (period_input.size() != 0 && padded) {
		var period_id = period_input.attr("value").substring("period_".length);
		var plesk_licence_id = plesk_licence_id_selected(os_id);
		var padded = $("input[id = 'plesk-added_" + os_id + "']").is(":checked");
		if (period_id && padded) {
			var plesk_period_id = $("input[id = 'plesk-period-id_" + os_id + "_period-id_" + period_id + "_plesk-licence-id_" + plesk_licence_id  + "']").attr("value");
		}
		return plesk_period_id
	}
	return false;
}


function swap_plesk_licence_choice(os_id, licence_input_id) {
	var plesk_licences = $("input[id^='licence_" + os_id + "']");
	plesk_licences.each( function() {
		if ($(this).attr("id") != licence_input_id) {
			$(this).removeAttr("checked");
		}
	});
	
	check_or_uncheck_30_domains_licence(os_id);
}

function plesk_licence_id_selected(os_id) {
	var padded = $("input[id ^='plesk-added_" + os_id + "']").is(":checked");
	var licence_input = $("input[id ^= 'licence_" + os_id + "']:checked");
	if (licence_input.size() != 0 && padded) {
		return licence_input.attr("value");
	}
	return false;
}

function set_previous_period_choice(os_id) {
	var prev = get_cookie("selected_subscription_period");
	if (prev) {
		var duration_input_id = $("input[id ^= 'period-duration_" + os_id + "'][value = '" + prev + "']").attr("id");
		var period_id = duration_input_id.substring(duration_input_id.lastIndexOf("_") + 1);
		var period_button = $("input[id = 'period_" + os_id + "_" + period_id + "']")
		period_button.attr("checked", "checked");
	}
}

function set_previous_plesk_added_choice(os_id) {
	var prev = get_cookie("plesk_added");
	if (prev == "yes") {
		$("input[id='plesk-added_" + os_id + "']").attr("checked", "checked");		
	} 
}

function set_previous_plesk_licence_choice(os_id) {
	var prev = get_cookie("selected_plesk_licence");
	if (prev) {
		var licence_id = "licence_" + os_id + "_" + prev;
		var licence_button = $("input[id = '"+ licence_id + "']");
		licence_button.attr("checked", "checked");
	}
}

function store_plesk_licence_choice(os_id) {
	var plesk_id = plesk_licence_id_selected(os_id);
	if (plesk_id) {
		document.cookie = "selected_plesk_licence=" + plesk_id + ";";
	}
}

function store_plesk_added_choice(plesk_checkbox) {
	var checked = plesk_checkbox.is(":checked");
	if (checked) {
		document.cookie = "plesk_added=yes;";
	} else {
		document.cookie = "plesk_added=no;";
	}
}

function store_period_choice(os_id) {
    var period_input = $("input[id ^= 'period_" + os_id + "_']:checked");
	if (period_input.size() > 0) {
		var period_id = period_input.attr("id").substring(period_input.attr("id").lastIndexOf("_") + 1);
		var period_duration_id = "period-duration_" + os_id + "_" + period_id;
		var period_duration = $("input[id ^='" + period_duration_id + "']").attr("value");
		if (period_duration) {
			document.cookie = "selected_subscription_period=" + period_duration + ";";
		}
	}
}

function get_os_id(element) {
	var os_id_full = element.attr('id');
	matches = os_id_full.match(/_{1}.{1,3}_{1}/);
	os_id = matches[0]
	return os_id.replace(/_/g, "");

}

function assign_periods_currency_symbol() {
	var period_labels = $("label[for ^= 'period_']");
	period_labels.each( function() {
		var region = $("input[name = 'region']").val();
		var currency_symbol = get_currency_symbol(region);

		var label_text = $(this).html().replace("EUR", currency_symbol);
		label_text = label_text.replace("&eur;", currency_symbol);
		label_text = label_text.replace("&pound;", currency_symbol);
		label_text = label_text.replace("$", currency_symbol);
		$(this).html(label_text);
	});
}

//Assign the Plesk Licence Price as per subscription period chosen
function assign_plesk_licence_price(os_id) {
	var padded = $("input[id ^='plesk-added_" + os_id + "']").is(":checked");
	if (plesk_available(os_id) && padded) {
		var period_id = period_id_selected(os_id);
		var duration = $("input[id = 'period-duration_" + os_id + "_" + period_id + "']").attr("value");
        
		var price_texts = $("span[id *= 'licence-price-span_" + os_id + "_']");
		price_texts.each(function() {
			var plesk_licence_id = $(this).attr("id").substring($(this).attr("id").lastIndexOf("_") + 1);
		    var price = $("input[id ^= 'licence-price_" + os_id + "_" + plesk_licence_id + "']").attr("value");
			var price_span_id = "licence-price-span_" + os_id + "_" + plesk_licence_id;
			var price_span = $("span[id = '" + price_span_id + "']");
			var region = $("input[name = 'region']").val();
			var price_text = "&raquo; " + get_currency_symbol(region) + ((price*1) * (duration*1)) + " / " + duration.replace(".0", "") + " months";
			price_span.html(price_text);
		});
	}
}

// Check or uncheck the 30 domains plesk licence input
function check_or_uncheck_30_domains_licence(os_id) {
	// If 100 / Unlimited licence are both unchecked, check 30 domains licence
	var all_unchecked = true;		
	var plesk_licences = $("input[id^='licence_" + os_id + "']");
	plesk_licences.each( function() {
		if (!$(this).attr("disabled") && $(this).attr("checked")) {
			all_unchecked = false;
		}
	});	

	var to_check = $("input[id^='licence_" + os_id + "']:disabled");
	if (all_unchecked) {
		to_check.attr("CHECKED", "checked");
		//to_check.html(to_check.html().replace("DISABLED", "CHECKED DISABLED"));
	} else {
		to_check.removeAttr("checked");	
	}
}

//The purchase link is displayed iff:
//	Plesk is not available and period option is checked OR
//	Plesk is available, a period option is checked and plesk has not been added OR
//	Plesk is available, a period option is checked, plesk has been added and a licence option is selected
function show_or_hide_purchase_link(os_id) {
	
	var pchecked = $("input[id ^='period_" + os_id + "']").is(":checked");
	var lchecked = $("input[id ^='licence_" + os_id + "']").is(":checked");
	var padded = $("input[id ^='plesk-added_" + os_id + "']").is(":checked");
	var expanded_os = $("input[id = 'current-os_" + os_id + "']").attr("value");

	var purchase_div = $("div[id='purchase_" + os_id + "']");
	if (expanded_os == "yes" && pchecked) { //(
		//(!plesk_available(os_id) && pchecked) ||  
		//( plesk_available(os_id) && pchecked && !padded) || 
		//( plesk_available(os_id) && pchecked &&  padded && lchecked))) {
		purchase_div.animate({ height: 'show', opacity: 'show' }, { duration:300, queue: "global" });
	} else {
		purchase_div.hide();
	}
}


//If plesk is unavailable, show plesk alert, else hide it
function show_or_hide_plesk_unavailable_alert(os_id) {
	var plesk_unavailable_div = $("div[id='plesk-unavailable-alert_" + os_id + "']");
	var expanded_os = $("input[id = 'current-os_" + os_id + "']").attr("value");
	if (expanded_os == "yes" && !plesk_available(os_id)) {
		plesk_unavailable_div.animate({ height: 'show', opacity: 'show' }, { duration:200, queue: "global" });
	} else {
		plesk_unavailable_div.hide();
	}
}

// Decide whether to display plesk if appropriate, based on the os id
function show_or_hide_plesk(os_id) {
	//Has a period option been selected and is plesk available?
	var pchecked = $("input[id ^='period_" + os_id + "']").is(":checked");
	var expanded_os = $("input[id = 'current-os_" + os_id + "']").attr("value");
	
	if (expanded_os == "yes" && plesk_available(os_id) && pchecked) {
		//Display the Plesk 8 option, and the licence option is the add plesk option is ticked
		var checked = $("#plesk-added_" + os_id).is(":checked");
		if(checked) {
			$("#plesk-licence-options_" + os_id).animate({ height: 'show', opacity: 'show' }, { duration:300, queue: "global" });
		} else {
			$("#plesk-licence-options_" + os_id).animate({ height: 'hide', opacity: 'hide' }, 'slow');
		}  
		var plesk_hidden = $("#plesk-options_" + os_id).is(":hidden");
		if (plesk_hidden) {
			$("#plesk-options_" + os_id).animate({ height: 'show', opacity: 'show' }, { duration:300, queue: "global" });
		}
	} else {
		//Hide all plesk options and plesk licence options
		$("#plesk-options_" + os_id).animate({ height: 'hide', opacity: 'hide' }, 'hide');
		$("#plesk-licence-options_" + os_id).animate({ height: 'hide', opacity: 'hide' }, 'hide');
	}
}

function show_or_hide_mgmt_option(os_id) {
	var period_selected = $("input[id ^='period_" + os_id + "']").is(":checked");
	var expanded_os = $("input[id = 'current-os_" + os_id + "']").attr("value");
	var plesk_added = $("#plesk-added_" + os_id).is(":checked");

	var mgmt_options = $("div[id = 'mgmt-option_" + os_id + "']");
	
	if (expanded_os == "yes" && period_selected && ((!plesk_added && mgmt_available(os_id)) || (plesk_added && mgmt_plesk_available(os_id)))) {
		mgmt_options.animate({ height: 'show', opacity: 'show' }, { duration:300, queue: "global" });
	} else {
		mgmt_options.animate({ height: 'hide', opacity: 'hide' }, 'hide');
	}
}

function show_selected_tab() {
	//Cycle through each tab and set opacity to 0.4 on all but the selected os type tab
	var current_type = $("input[id='plan_type']").attr('value');
	var tabs = $("li[id ^='plan-type-tab_']");
	tabs.each(function() {
		var tab_type = $(this).attr("id").substring("plan-type-tab_".length);
		if (current_type !== tab_type) {
			$(this).animate({opacity:0.3});
		} else {
			$(this).animate({opacity:1.0});
		}
	});
}

//Compact non-selected oss and animate them to the bottom of the page
function animate_non_selected(selected_os_id) {
	var i = 1;
	selected_os_id = "os_" + selected_os_id + "_container";
	
	//Set the position you want the non-selected oss to animate to
	var x_const = -180;
	var y_const = -420;
	do {
		//Get the current os element
		var	os_id = $("#os_" + i + "_container").attr('id');
		
		//If it's not the selected os, put it into the animation queue
		if (selected_os_id != os_id) {
			//Remove the flag in the selected os hidden input
			$("#current-os_" + i).val("no");

			//Hide All Options
			show_or_hide_plesk_unavailable_alert(i);
			show_or_hide_plesk(i);
			show_or_hide_purchase_link(i);
			show_or_hide_mgmt_option(i);
			
			//Set the mouse cursor/pointer to a pointer cursor
			$("#os_" + i + "_container").css("cursor", "pointer");

			//Increment the x and y positions as each os is put in the animation queue
			y_const += 120;
			var x_pos = x_const + "px";
			var y_pos = y_const + "px";

			//Hide all period and plesk options
			$("#period-options_" + i).hide("fast");
			$("#plesk-options_" + i).hide("fast");
			$("#plesk-licence-options_" + i).hide("fast");


			//Put the element and new position in the animation queue
			var curr_os = $("#" + os_id);
			$(curr_os).animate( { height: "120px", width: "135px"}, { duration: 100 } )
						.animate( { "left":x_pos, "top":y_pos }, { duration: 500});
						//.animate( { "top":y_pos }, { duration: 300})
						//.animate( { fontSize:"100%" }, { duration: 300})
						//.animate( { opacity: 0.6 }, { duration:300, queue: "global" });
			//$(curr_os).animate( { height: "120px", width: "120px", left: x_pos, top: y_pos }, { duration: "normal" });
			
			//Change the background image to back to its original
			var bg = curr_os.css("background-image");
			if (bg) {
				bg = bg.replace("corner", "fade_smaller");
				curr_os.css("background-image", bg);
                //Ensure it doesn't tile
				curr_os.css("background-repeat", "no-repeat");
			}

		} else {
            $("#current-os_" + i).val("yes");
		} 
		i++;
	} while (document.getElementById(os_id))
} 

function expand_selected_os(os_id) {
    //Set the mouse cursor/pointer to a default cursor
	var container = $("#os_" + os_id + "_container")
	var style = container.css("cursor");
	container.css("cursor", "default");

	//Change the background image to fade slice
    var bg = container.css("background-image");
	bg = bg.replace("fade_smaller", "corner");
    container.css("background-image", bg)
    container.css("background-repeat", "no-repeat")

    //Start loading up the animation queue
    //Animate the selected os - expand it and move it to the top-left of the container 
    container.animate( {height:"500px", 
						width:"450px", 
						left:"0px", 
						top:"0px", opacity: 1.0}, 
					   {duration: "normal", 
						queue: "global"});
    //container.animate( { height:"500px", width:"450px", left:"0px", top:"0px" }, { duration: "normal", queue: "global"});
    //After animation above, show the period options for the selected os
    $("#period-options_" + os_id).animate( {height: 'show', 
											opacity: 'show' }, 
										   {duration: "normal", 
											queue: "global" });

    //Execute the Queue if it's not empty
    //if ( $.fxqueue("global").length > 0 )
    //    $.fxqueue("global").start();
    //else
    //animation();
   
	assign_plesk_licence_price(os_id);
	//assign_periods_currency_symbol();
	show_or_hide_plesk_unavailable_alert(os_id);
    show_or_hide_plesk(os_id);
    show_or_hide_purchase_link(os_id);
	show_or_hide_mgmt_option(os_id);
}

//Get cookie based on a search string
function get_cookie(Name) {
	var search_str = Name + "=";
	var value = "";
	if (document.cookie.length > 0) {
		name_start = document.cookie.indexOf(search_str);

		// if cookie exists
		if (name_start != -1) { 
			name_start += search_str.length;

			// set index of beginning of value
			pair_end = document.cookie.indexOf(";", name_start);

			// set index of end of cookie value
			if (pair_end == -1) {
				pair_end = document.cookie.length;
			}
			value=unescape(document.cookie.substring(name_start, pair_end));
		}
	}
	return value;
}

function remove_cookie(name)
{
	var cookie_string = document.cookie;
	var cookie_date = new Date ( );  // current date & time
	cookie_date.setTime ( cookie_date.getTime() - 1 );
	document.cookie = name + "=; expires=" + cookie_date.toGMTString() + ";";
	var cookie_string = document.cookie;
	var c = cookie_string;
}

function reset_page() {
	var radios_checkboxes = $("input[type = 'checkbox']:checked, input[type = 'radio']:checked");
	radios_checkboxes.each(function() {
		var checked = $(this).attr("id");
		document.getElementById(checked).checked = false;
	});
		
	remove_cookie("selected_os_id");
	remove_cookie("selected_subscription_period");
	remove_cookie("selected_plesk_licence");
	remove_cookie("plesk_added");
	window.location.reload();
}
