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 getBezelByModelName(model) {
	return {
		"pebble_time_round_silver_14":		       "pebble-time-round-14mm-silver",
		"pebble_time_round_black_14":		       "pebble-time-round-14mm-black",
		"pebble_time_round_rose_gold_14":		   "pebble-time-round-14mm-rose-gold",
		"pebble_time_round_silver_20":		       "pebble-time-round-20mm-silver",
		"pebble_time_round_black_20":		       "pebble-time-round-20mm-black",
		
		"pebble_time_steel_black":		           "pebble-time-steel-black",
		"pebble_time_steel_silver":		           "pebble-time-steel-silver",
		"pebble_time_steel_gold":		           "pebble-time-steel-gold",
		
		"pebble_time_red":		                   "pebble-time-red",
		"pebble_time_white":		               "pebble-time-white",
		"pebble_time_black":		               "pebble-time-black",
		
		"pebble_steel_silver":		               "pebble-steel-silver",
		"pebble_steel_black":		               "pebble-steel-black",
		
		"pebble_black":		                       "pebble-black",
		"pebble_grey":		                       "pebble-grey",
		"pebble_white":		                       "pebble-white",
		"pebble_red":		                       "pebble-red",
		"pebble_orange":		                   "pebble-orange",
		"pebble_blue":		                       "pebble-blue",
		"pebble_green":		                       "pebble-green",
		"pebble_pink":		                       "pebble-pink"

	}[model.replace(/mm$/, '')];
}

function getVariationByName(name) {
	return ["Diamond", "Ruby", "Fire", "Forest", "Snow"].indexOf(name) != -1;
}

function updatePreview() {
    var n = '';
    var o2 = '';
    var o = '';
    var b = '';
    var r = '';
    if (parse('bw') != 'true') {
        n = 'img/n-'+$('#num_color').val().replace(' ', '-')+'.png';
        o2 = 'img/0-'+$('#num_color').val().replace(' ', '-')+'.png';
        o = 'img/o-'+$('#orn_color').val().replace(' ', '-')+'.png';
        b = 'img/b-'+$('#bg_color').val().replace(' ', '-')+'.png';
        r = 'img/r-'+$('#orn_color').val().replace(' ', '-')+'.png';
    } else {
        if ($('#invert').prop("checked")) {
            n = 'img/n-Black.png';
            o2 = 'img/0-Black.png';
            o = 'img/o-Black.png';
            b = 'img/b-White.png';
        } else {
            n = 'img/n-White.png';
            o2 = 'img/0-White.png';
            o = 'img/o-White.png';
            b = 'img/b-Black.png';
        }
        if($('#monochrome').prop("checked")) {
            o = 'img/o-Aplite-Gray.png';
        }
    }

    $('.preview-n').attr('src', n);
    $('.preview-o').attr('src', o);
    $('.preview-b').attr('src', b);
    $('.preview-o2').attr('src', o2);
    if (parse('bw') != 'true') {
        $('.preview-r').attr('src', r);
    }
    
    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');
    }
    if ($('#size').prop("checked") && parse('rect') == 'true') {
        $('.preview-scaler').addClass('scaled');
    } else {
        $('.preview-scaler').removeClass('scaled');
    }
}

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

function updateNightsaver() {
    if ($('#nightsaver').prop("checked")) {
        $('.show-on-nightsaver').show();
    } else {
        $('.show-on-nightsaver').hide();
    }
}

$('#nightsaver').on('change', function() {
    updateNightsaver();
});

function updateRound() {
    if (parse('rect') != 'true') {
        $('.preview').addClass('round-preview');
    }
}

(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"),
	    btvibe: ''+$("#btvibe").prop("checked"),
	    contrast: ''+$("#contrast").prop("checked"),
	    nightsaver: ''+$("#nightsaver").prop("checked"),
	    ns_start: $("#ns_start").val(),
	    ns_stop: $("#ns_stop").val(),
	    backlight: ''+$("#backlight").prop("checked"),
	    weekday: ''+$("#weekday").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"),
			btvibe: ''+$("#btvibe").prop("checked"),
			contrast: ''+$("#contrast").prop("checked"),
			nightsaver: ''+$("#nightsaver").prop("checked"),
			ns_start: $("#ns_start").val(),
			ns_stop: $("#ns_stop").val(),
			backlight: ''+$("#backlight").prop("checked"),
			weekday: ''+$("#weekday").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'));
			$("#btvibe").prop("checked", (stored.btvibe === 'true'));
			$("#contrast").prop("checked", (stored.contrast === 'true'));
			$("#nightsaver").prop("checked", (stored.nightsaver === 'true'));
			if (stored.ns_start) { $("#ns_start").val(stored.ns_start); }
			if (stored.ns_start) { $("#ns_stop").val(stored.ns_stop); }
			$("#backlight").prop("checked", (stored.backlight === 'true'));
			$("#weekday").prop("checked", (stored.weekday === 'true'));
		}
		updatePreview();
		updateNightsaver();
        updateRound();
	}
}



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();
  }
  
  var bezelimg = 'chalk';
  var previewhardware = 'for-chalk';
  
  if(parse('model') != "Not found" && getBezelByModelName(parse('model')) != undefined) {
      console.log('model string present: '+parse('model'));
      bezelimg = getBezelByModelName(parse('model'));
      console.log('image name: '+bezelimg);
  } else {
      if(parse('rect') == 'true') {
          bezelimg = 'basalt';
          if(parse('bw') == 'true') {
              bezelimg = 'aplite';
          }
      }
  }
  if(parse('rect') == 'true') {
      previewhardware = 'for-basalt';
      if(parse('bw') == 'true') {
          previewhardware = 'for-aplite';
      }
  }
  $('.previewbezel').css('background-image', 'url(frames/'+bezelimg+'.png)');
  $('.previewbezel, .preview').addClass(previewhardware);
  
  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;
}