function parse(val) {
    var result = "Not found",
        tmp = [];
    location.search
    //.replace ( "?", "" ) 
    // this is better, there might be a question mark inside
    .substr(1)
        .split("&")
        .forEach(function (item) {
        tmp = item.split("=");
        if (tmp[0] === val) result = decodeURIComponent(tmp[1]);
    });
    return result;
}

function getColorByName(name) {
	return {
		"Diamond":		   202,
		"Ruby": 		   226,
		"Fire":			   224,
		"Forest":		   200,
		"Red":			   240,
		"Green":		   204,
		"Blue":			   195,
		"Yellow":		   252,
		"Cyan":			   207,
		"Magenta":		   243,
		"Violet":		   227,
		"Orange":		   244,
		"Vivid Cerulean":  203,
		"Chrome Yellow":   248,
		"Spring Green":	   206,
		"Black":		   192,
		"Dark Gray":	   213,
		"Light Gray":	   234,
		"White":		   255
	}[name];
}
function getVariationByName(name) {
	return ["Diamond", "Ruby", "Fire", "Forest"].indexOf(name) != -1;
}

function updatePreview() {
    var n = 'img/n-'+$('#num_color').val().replace(' ', '-')+'.png';
    var o2 = 'img/0-'+$('#num_color').val().replace(' ', '-')+'.png';
    var o = 'img/o-'+$('#orn_color').val().replace(' ', '-')+'.png';
    var b = 'img/b-'+$('#bg_color').val().replace(' ', '-')+'.png';

    $('.preview-n').attr('src', n);
    $('.preview-o').attr('src', o);
    $('.preview-b').attr('src', b);
    $('.preview-o2').attr('src', o2);
    
    if ($('#zero').prop("checked")) {
        $('.showzero').addClass('activeshowzero');
    } else {
        $('.showzero').removeClass('activeshowzero')
    }
    
    if ($('#date').prop("checked")) {
        $('.eurodate').addClass('activeeurodate');
    } else {
        $('.eurodate').removeClass('activeeurodate')
    }
    
    if ($('#center').prop("checked") && $('#date').prop("checked")) {
        $('.preview-centeralign').addClass('activecenteralign');
    } else {
        $('.preview-centeralign').removeClass('activecenteralign')
    }
}

$('#num_color, #orn_color, #bg_color, #date, #zero, #center').on('change', function() {
    updatePreview();
});

(function() {
  loadOptions();
  submitHandler();
})();

function getDataToSend() {
	bg_color = $("#bg_color").val();
	num_color = $("#num_color").val();
	orn_color = $("#orn_color").val();
	data = {
	    large_mode: ''+$("#size").prop("checked"),
	    eu_date: ''+$("#date").prop("checked"),
	    quick_start: ''+$("#delay").prop("checked"),
	    leading_zero: ''+$("#zero").prop("checked"),
	    background_color: getColorByName(bg_color),
	    number_base_color: getColorByName(num_color),
	    number_variation: 0+getVariationByName(num_color),
	    ornament_base_color: getColorByName(orn_color),
	    ornament_variation: 0+getVariationByName(orn_color),
	    invert: ''+$("#invert").prop("checked"),
	    monochrome: ''+$("#monochrome").prop("checked"),
	    center: ''+$("#center").prop("checked"),
	};
	return data;
}

function saveData(){
	if(localStorage) {
		toStore = {
			size: ''+$("#size").prop("checked"),
			date: ''+$("#date").prop("checked"),
			delay: ''+$("#delay").prop("checked"),
			zero: ''+$("#zero").prop("checked"),
			bg_color: $("#bg_color").val(),
			num_color: $("#num_color").val(),
			orn_color: $("#orn_color").val(),
			invert: ''+$("#invert").prop("checked"),
			monochrome: ''+$("#monochrome").prop("checked"),
			center: ''+$("#center").prop("checked")
		};
		localStorage.setItem("lastconfig", JSON.stringify(toStore));
	}
}

function restoreData(){
	if(localStorage) {
		stored = JSON.parse(localStorage.getItem("lastconfig"));
		if(stored){
			$("#size").prop("checked", (stored.size === 'true'));
			$("#date").prop("checked", (stored.date === 'true'));
			$("#delay").prop("checked", (stored.delay === 'true'));
			$("#zero").prop("checked", (stored.zero === 'true'));
			$("#bg_color").val(stored.bg_color);
			$("#num_color").val(stored.num_color);
			$("#orn_color").val(stored.orn_color);
			$("#invert").prop("checked", (stored.invert === 'true'));
			$("#monochrome").prop("checked", (stored.monochrome === 'true'));
			$("#center").prop("checked", (stored.center === 'true'));
		}
		updatePreview();
	}
}



function submitHandler() {
  var $submitButton = $('#send');

  $submitButton.on('click', function() {
    console.log('Submit');

    var return_to = getQueryParam('return_to', 'pebblejs://close#');
    document.location = return_to + encodeURIComponent(JSON.stringify(getAndStoreConfigData()));
  });
}

function loadOptions() {
  if(parse('rect') == 'true') {
      // $('.recthide').hide();
  } else {
      $('.roundhide').hide();
  }
  if(parse('bw') == 'true') {
      $('.bwhide').hide();
  } else {
      $('.colorhide').hide();
  }
  restoreData();
}

function getAndStoreConfigData() {
  saveData();
  return getDataToSend();
}

function getQueryParam(variable, defaultValue) {
  var query = location.search.substring(1);
  var vars = query.split('&');
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');
    if (pair[0] === variable) {
      return decodeURIComponent(pair[1]);
    }
  }
  return defaultValue || false;
}