$(document).ready( function() {
	//clear priority and other tasks if people reload the page or lost connection while a wizard was active
	$(hyperion).one("ready", function(event) {	
		if(getStorage("wizardactive") === 'true')	
		{
			requestPriorityClear();
			setStorage("wizardactive", false);
			if(getStorage("kodiAddress" != null))
			{
				kodiAddress = getStorage("kodiAddress");
				sendToKodi("stop");
			}
		}
	});
	
	function resetWizard()
	{
		$("#wizard_modal").modal('hide');
		clearInterval(wIntveralId);
		requestPriorityClear();
		setStorage("wizardactive", false);
		$('#wizp1').toggle(true);
		$('#wizp2').toggle(false);
		$('#wizp3').toggle(false);
		//cc
		if(withKodi)
			sendToKodi("stop");
		step = 0;
	}
	
	//rgb byte order wizard
	var wIntveralId;
	var new_rgb_order;
	function changeColor()
	{
		var color = $("#wiz_canv_color").css('background-color');
		if (color == 'rgb(255, 0, 0)')
		{
			$("#wiz_canv_color").css('background-color','rgb(0, 255, 0)');
			requestSetColor('0','255','0');
		}
		else
		{
			$("#wiz_canv_color").css('background-color','rgb(255, 0, 0)');
			requestSetColor('255','0','0');
		}
	}
	function startWizardRGB()
	{
		//create html
		$('#wiz_header').html(' '+$.i18n('wiz_rgb_title'));
		$('#wizp1_body').html('
'+$.i18n('wiz_rgb_title')+' '+$.i18n('wiz_rgb_intro1')+'
'+$.i18n('wiz_rgb_intro2')+'
');
		$('#wizp1_footer').html(' '+$.i18n('general_btn_continue')+' '+$.i18n('general_btn_cancel')+' ');
		$('#wizp2_body').html(''+$.i18n('wiz_rgb_expl')+'
');
		$('#wizp2_body').append('');
		$('#wizp2_body').append(''+$.i18n('wiz_rgb_q')+' ');
		$('#wizp2_body').append(''+$.i18n('wiz_rgb_qrend')+' '+$.i18n('wiz_rgb_qgend')+' 
');
		$('#wizp2_footer').html(' '+$.i18n('general_btn_saverestart')+' '+$.i18n('general_btn_ok')+' '+$.i18n('general_btn_cancel')+' ')
		
		//open modal
		$("#wizard_modal").modal({
			backdrop : "static",
			keyboard: false,
			show: true
		});
		
		//listen for continue
		$('#btn_wiz_cont').off().on('click',function() {
			beginWizardRGB();
			$('#wizp1').toggle(false);
			$('#wizp2').toggle(true);
		});
	}
	function beginWizardRGB()
	{	
		$("#wiz_switchtime_select").off().on('change',function() {
			clearInterval(wIntveralId);
			var time = $("#wiz_switchtime_select").val();
			wIntveralId = setInterval(function() { changeColor(); }, time*1000);
		});
		$('.wselect').change(function () {
			var rgb_order = serverConfig.device.colorOrder.split("");
			var redS = $("#wiz_r_select").val();
			var greenS = $("#wiz_g_select").val();
			var blueS = rgb_order.toString().replace(/,/g,"").replace(redS, "").replace(greenS,"");
		
			for (var i = 0; i '+$.i18n('wiz_cc_kodishould',$.i18n('edt_conf_color_white_title'));
				sendToKodi('playP',"white");
			}
			else
				h += ' '+$.i18n('wiz_cc_lettvshow',$.i18n('edt_conf_color_white_title'));
			$('#wiz_cc_desc').html(h);
		}
		if(step == 3)
		{
			updateWEditor(["gammaRed","gammaGreen","gammaBlue"]);
			h = ''+$.i18n('wiz_cc_adjustgamma')+'
';
			if(withKodi)
			{
				sendToKodi('playP',"HGradient");
				h +=''+$.i18n('wiz_cc_btn_switchpic')+' ';
			}
			else
				h += ''+$.i18n('wiz_cc_lettvshowm', "gey_1, grey_2, grey_3, HGradient, VGradient")+'
';
			$('#wiz_cc_desc').html(h);
			$('#wiz_cc_btn_sp').off().on('click', function(){
					switchPicture(["VGradient","grey_1","grey_2","grey_3","HGradient"]);
			});
		}
		if(step == 4)
		{
			updateWEditor(["red"]);
			h = $.i18n('wiz_cc_adjustit',$.i18n('edt_conf_color_red_title'));
			if(withKodi)
			{
				h += ' '+$.i18n('wiz_cc_kodishould',$.i18n('edt_conf_color_red_title'));	
				sendToKodi('playP',"red");
			}
			else
				h += ' '+$.i18n('wiz_cc_lettvshow',$.i18n('edt_conf_color_red_title'));
			$('#wiz_cc_desc').html(h);
		}
		if(step == 5)
		{
			updateWEditor(["green"]);
			h = $.i18n('wiz_cc_adjustit',$.i18n('edt_conf_color_green_title'));
			if(withKodi)
			{
				h += ' '+$.i18n('wiz_cc_kodishould',$.i18n('edt_conf_color_green_title'));	
				sendToKodi('playP',"green");
			}
			else
				h += ' '+$.i18n('wiz_cc_lettvshow',$.i18n('edt_conf_color_green_title'));
			$('#wiz_cc_desc').html(h);
		}
		if(step == 6)
		{
			updateWEditor(["blue"]);
			h = $.i18n('wiz_cc_adjustit',$.i18n('edt_conf_color_blue_title'));
			if(withKodi)
			{
				h += ' '+$.i18n('wiz_cc_kodishould',$.i18n('edt_conf_color_blue_title'));
				sendToKodi('playP',"blue");
			}
			else
				h += ' '+$.i18n('wiz_cc_lettvshow',$.i18n('edt_conf_color_blue_title'));
			$('#wiz_cc_desc').html(h);
		}
		if(step == 7)
		{
			updateWEditor(["cyan"]);
			h = $.i18n('wiz_cc_adjustit',$.i18n('edt_conf_color_cyan_title'));
			if(withKodi)
			{
				h += ' '+$.i18n('wiz_cc_kodishould',$.i18n('edt_conf_color_cyan_title'));
				sendToKodi('playP',"cyan");
			}
			else
				h += ' '+$.i18n('wiz_cc_lettvshow',$.i18n('edt_conf_color_cyan_title'));
			$('#wiz_cc_desc').html(h);
		}
		if(step == 8)
		{
			updateWEditor(["magenta"]);
			h = $.i18n('wiz_cc_adjustit',$.i18n('edt_conf_color_magenta_title'));
			if(withKodi)
			{
				h += ' '+$.i18n('wiz_cc_kodishould',$.i18n('edt_conf_color_magenta_title'));
				sendToKodi('playP',"magenta");
			}
			else
				h += ' '+$.i18n('wiz_cc_lettvshow',$.i18n('edt_conf_color_magenta_title'));
			$('#wiz_cc_desc').html(h);
		}
		if(step == 9)
		{
			updateWEditor(["yellow"]);
			h = $.i18n('wiz_cc_adjustit',$.i18n('edt_conf_color_yellow_title'));
			if(withKodi)
			{
				h += ' '+$.i18n('wiz_cc_kodishould',$.i18n('edt_conf_color_yellow_title'));
				sendToKodi('playP',"yellow");
			}
			else
				h += ' '+$.i18n('wiz_cc_lettvshow',$.i18n('edt_conf_color_yellow_title'));
			$('#wiz_cc_desc').html(h);
		}
		if(step == 10)
		{
			updateWEditor(["brightnessMin"]);
			h = $.i18n('wiz_cc_minBright');
			if(withKodi)
			{
				h += ' '+$.i18n('wiz_cc_kodishould',$.i18n('edt_conf_color_black_title'));
				sendToKodi('playP',"black");
			}
			else
				h += ' '+$.i18n('wiz_cc_lettvshow',$.i18n('edt_conf_color_black_title'));
			$('#wiz_cc_desc').html(h);
		}
		if(step == 11)
		{
			updateWEditor([""], true);
			h = ''+$.i18n('wiz_cc_testintro')+'
';
			if(withKodi)
			{
				h += ''+$.i18n('wiz_cc_testintrok')+'
';
				sendToKodi('stop');
				for(var i = 0; i  '+txt+' ';
				}
				h +='  '+$.i18n('wiz_cc_btn_stop')+'
';
			}
			else
				h += ''+$.i18n('wiz_cc_testintrowok')+' '+$.i18n('wiz_cc_link')+' 
';
			h += ''+$.i18n('wiz_cc_summary')+'
';
			$('#wiz_cc_desc').html(h);
			
			$('.videobtn').off().on('click', function(e){
				if(e.target.id == "stop")
					sendToKodi("stop");
				else
					sendToKodi("playV",e.target.id+'.mp4');
				
				$(this).attr("disabled", true);
				setTimeout(function(){$('.videobtn').attr("disabled", false)},10000);
			});
			
			$('#btn_wiz_next').attr("disabled", true);
			$('#btn_wiz_save').toggle(true);
		}
		else
		{
			$('#btn_wiz_next').attr("disabled", false);
			$('#btn_wiz_save').toggle(false);
		}
	}
	
	function updateWEditor(el, all)
	{
		for (var key in cobj)
		{
			if(all === true || el[0] == key || el[1] == key || el[2] == key)
				$('#editor_container_wiz [data-schemapath*=".'+profile+'.'+key+'"]').toggle(true);
			else
				$('#editor_container_wiz [data-schemapath*=".'+profile+'.'+key+'"]').toggle(false);
		}
	}
	
	function startWizardCC()
	{
		//create html
		$('#wiz_header').html(' '+$.i18n('wiz_cc_title'));
		$('#wizp1_body').html(''+$.i18n('wiz_cc_title')+' '+$.i18n('wiz_cc_intro1')+'
'+$.i18n('wiz_cc_kwebs')+'  ');
		$('#wizp1_footer').html(' '+$.i18n('general_btn_continue')+' '+$.i18n('general_btn_cancel')+' ');
		$('#wizp2_body').html('
');
		$('#wizp2_footer').html(' '+$.i18n('general_btn_back')+''+$.i18n('general_btn_next')+'  '+$.i18n('general_btn_saverestart')+' '+$.i18n('general_btn_cancel')+' ')
		
		//open modal
		$("#wizard_modal").modal({
			backdrop : "static",
			keyboard: false,
			show: true
		});
		
		$('#wiz_cc_kodiip').off().on('change',function() {
			kodiAddress = $(this).val();
			setStorage("kodiAddress", kodiAddress);
			sendToKodi("msg", $.i18n('wiz_cc_kodimsg_start'), function(cb){
				if(cb == "error")
				{
					$('#kodi_status').html(''+$.i18n('wiz_cc_kodidiscon')+'
'+$.i18n('wiz_cc_kodidisconlink')+' '+$.i18n('wiz_cc_link')+' 
');
					withKodi = false;
				}
				else
				{
					$('#kodi_status').html(''+$.i18n('wiz_cc_kodicon')+'
');
					withKodi = true;
				}
				
				$('#btn_wiz_cont').attr('disabled', false);
			});
		});
		
		//listen for continue
		$('#btn_wiz_cont').off().on('click',function() {
			beginWizardCC();
			$('#wizp1').toggle(false);
			$('#wizp2').toggle(true);
		});
		
		$('#wiz_cc_kodiip').trigger("change")
		colorLength = serverConfig.color.channelAdjustment;
		cobj = schema.color.properties.channelAdjustment.items.properties;
		websAddress = document.location.hostname+':'+serverConfig.webConfig.port;
		imgAddress = 'http://'+websAddress+'/img/cc/';
		setStorage("wizardactive", true);
		
		//check profile count
		if(colorLength.length > 1)
		{
			$('#multi_cali').html(''+$.i18n('wiz_cc_morethanone')+'
 ');
			for(var i = 0; i'+$.i18n('wiz_hue_title'));
		$('#wizp1_body').html(''+$.i18n('wiz_hue_title')+' '+$.i18n('wiz_hue_intro1')+'
'+$.i18n('wiz_hue_intro2')+'
');
		$('#wizp1_footer').html(' '+$.i18n('general_btn_continue')+' '+$.i18n('general_btn_cancel')+' ');
		$('#wizp2_body').append(''+$.i18n('wiz_hue_failure_ip')+' ');
		$('#wizp2_body').append(''+$.i18n('wiz_hue_failure_connection')+'  ');
		$('#wizp2_body').append('');
		$('#wizp2_body').append(''+$.i18n('wiz_hue_username')+' 
');
		$('#wizp2_body').append('');
		$('#wizp2_footer').html('  '+$.i18n('wiz_hue_create_user')+'  '+$.i18n('general_btn_cancel')+' ');
		$('#wizp3_body').html(''+$.i18n('wiz_hue_press_link')+'  ');
		//open modal
		$("#wizard_modal").modal({
			backdrop : "static",
			keyboard: false,
			show: true
		});
		//listen for continue
		$('#btn_wiz_cont').off().on('click',function() {
			beginWizardHue();
			$('#wizp1').toggle(false);
			$('#wizp2').toggle(true);
		});
	}
	function beginWizardHue()
	{
		//listen for continue
		$('#wiz_hue_create_user').off().on('click',function() {
			doWizardHue();
		});
	}
	function doWizardHue()
	{
	    var connectionRetries = 15;
			var data = {"devicetype":"hyperion#"+Date.now()};
			var UserInterval = setInterval(function(){
			$.ajax({
				type: "POST",
				url: 'http://'+$("#ip").val()+'/api',
				processData: false,
				timeout: 1000,
				contentType: 'application/json',
				data: JSON.stringify(data),
				success: function(r) {
						$('#wizp1').toggle(false);
						$('#wizp2').toggle(false);
						$('#wizp3').toggle(true);
						connectionRetries--;
						$("#connectionTime").html(connectionRetries);
						if(connectionRetries == 0) {
							abortConnection(UserInterval);
	          }
						else
						{
							$("#abortConnection").hide();
							$("#ip_alert").hide();
							if (typeof r[0].error != 'undefined') {
								console.log(connectionRetries+": link not pressed");
							}
						  if (typeof r[0].success != 'undefined') {
								$('#wizp1').toggle(false);
								$('#wizp2').toggle(true);
								$('#wizp3').toggle(false);
								$('#user').val(r[0].success.username);
								$( "#hue_lights" ).empty();
								get_hue_lights();
								clearInterval(UserInterval);
						  }
						}
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					$('#wizp1').toggle(false);
					$('#wizp2').toggle(true);
					$('#wizp3').toggle(false);
					$("#ip_alert").show();
					clearInterval(UserInterval);
				 }
			});
	  },1000);
	}
	function get_hue_lights(){
		$.ajax({
			type: "GET",
			url: 'http://'+$("#ip").val()+'/api/'+$("#user").val()+'/lights',
			processData: false,
			contentType: 'application/json',
			success: function(r) {
				for(var lightid in r){
					$('#hue_lights').append('ID: '+lightid+' Name: '+r[lightid].name+'  ');
				}
			}
		});
	}
	function abortConnection(UserInterval){
		clearInterval(UserInterval);
		$('#wizp1').toggle(false);
		$('#wizp2').toggle(true);
		$('#wizp3').toggle(false);
		$("#abortConnection").show();
	}
	
	$('#btn_wizard_philipshue').off().on('click',startWizardPhilipsHue);
	
});