var Lock_language = 'en';
var Lock_languages = {};
var Lock_plugins = [];
var Lock_bundles = {};

function pageLoad() {

  populateClock();
  populatePluginsList();
  loadSettings('general');
}

function setLang(lang) {
  document.write('<script type="text/javascript" src="lang/en.js"><\/script>');
  
  if((typeof lang == 'undefined') || (lang == 'default')) {
  	var language=(navigator.language || navigator.userLanguage);
  	
    document.write('<script type="text/javascript" src="lang/'+language.substring(0,2)+'.js"><\/script>');
    document.write('<script type="text/javascript" src="lang/'+language+'.js"><\/script>');
    
    Lock_language = language;
  }
  else
    document.write('<script type="text/javascript" src="lang/'+lang+'.js"><\/script>');
}

function loadBundle(bundle) {
  
  var link = document.createElement('link');
  link.setAttribute("rel", "stylesheet")
  link.setAttribute("type", "text/css")
  link.setAttribute("href", 'bundles/'+bundle+'/bundle.css');
  
  Lock_bundles[bundle] = document.body.appendChild(link);
}

function removeBundle(bundle) {
  if(Lock_bundles[bundle])
    Lock_bundles[bundle].remove();
}

function toggleBundle(that) {
  if(that.checked)
    loadBundle(that.value);
  else
    removeBundle(that.value);
}

function loadPlugins() {
  var included = [];
  
  for(var i=0; i<plugins.length; i++) {
    if(plugins[i].indexOf(':') != -1)
      var pName = plugins[i].substring(0,plugins[i].indexOf(':'));
    else
      var pName = plugins[i];
    
    if(included.include(pName))
      continue;
    
    document.write('<script type="text/javascript" src="plugins/'+pName+'/settings.js"><\/script>');
    document.write('<script type="text/javascript" src="plugins/'+pName+'/plugin.js"><\/script>');
    document.write('<link rel="stylesheet" type="text/css" href="plugins/'+pName+'/plugin.css" />');
  }
}

function loadSettings(name) {
  if(name.indexOf(':') != -1) {
    pName = String(name).replace(/([:\s])/i,'.');
    vname = name.substring(0,name.indexOf(':'));
    name = name.replace(/([\.:\s])/i,'-');
    eval('var settings = (Settings.'+vname+' && Settings.'+pName+')?Settings.'+pName+':Settings.'+vname+';');
  }
  else
    eval('var settings = Settings.'+name+';');
  
  if(typeof settings == 'undefined')
    return ;
  
  var form = $('settings');
  
  var fieldset = document.createElement('fieldset');
  fieldset.id = name+'-settings';
  fieldset.style.display = 'none';
   var legend = document.createElement('legend');
   legend.innerHTML = String(settings.desc);
  fieldset.appendChild(legend);
  
  for(var i in settings) {
    if(typeof settings[i] != 'object' || typeof settings[i].desc == 'undefined')
      continue;
    
    var label = document.createElement('label');
    label.innerHTML = settings[i].desc+'&nbsp;:';
    fieldset.appendChild(label);
    fieldset.appendChild(document.createElement('br'));
    
    if(typeof settings[i].choices == 'string') {
      if(settings[i].choices == 'languages') {
        
        var values = [{label: 'Auto Detect', value: 'default'}].concat(Lock_languages_av);
        var list = document.createElement('select');
        list.name = 'settings['+name+']['+i+']';
        for(var j=0; j<values.length; j++) {
          var option = document.createElement('option');
          
          if(typeof values[j] == 'object') {
            option.value = values[j].value;
            option.innerHTML = values[j].label;
          }
          else {
            option.value = values[j];
            option.innerHTML = values[j];
          }
          
          list.appendChild(option);
        }
        fieldset.appendChild(list);
      }
    }
    else {
      switch(settings[i].choices.type) {
        case 'list':
          var values = settings[i].choices.values;
          var list = document.createElement('select');
          list.name = 'settings['+name+']['+i+']';
          for(var j=0; j<values.length; j++) {
            var option = document.createElement('option');
            option.value = values[j].value;
            option.innerHTML = values[j].label;
            
            if(String(settings[i].defValue) == values[j].value)
              option.selected = true;
            
            list.appendChild(option);
          }
          fieldset.appendChild(list);
        break;
        
        case 'radio':
          var values = settings[i].choices.values;
          
          for(var j=0; j<values.length; j++) {
            var label = document.createElement('label');
            
            var radio = document.createElement('input');
            radio.type = 'radio';
            radio.name = 'settings['+name+']['+i+']';
            radio.value = values[j].value;
            
            if(String(settings[i].defValue) == values[j].value)
              radio.checked = true;
            
            label.appendChild(radio);
            label.appendChild(document.createTextNode(' '+values[j].label));
            fieldset.appendChild(label);
            fieldset.appendChild(document.createElement('br'));
          }
          
        break;
        
        case 'input':
          var input = document.createElement('input');
          input.type = 'text';
          input.name = 'settings['+name+']['+i+']';
          input.value = settings[i].defValue;
          
          if(settings[i].choices.size)
            input.size = settings[i].choices.size;
          
          if(settings[i].choices.regex) {
            input.regex = settings[i].choices.regex;
            input.onkeyup = function(){if(this.regex.test(this.value)) alert('Invalid Data!');};
          }
          else if(settings[i].choices.check) {
            input.check = settings[i].choices.check;
            input.onkeyup = function() { if(!this.check(this.value)) alert('Invalid Data!'); };
          }
          
          fieldset.appendChild(input);
      }
    }
    
    fieldset.appendChild(document.createElement('br'));
    fieldset.appendChild(document.createElement('br'));
  }
  
  new Effect.Appear(form.appendChild(fieldset), {duration: 1});
}


function populateClock() {
  $('date').innerHTML = new Date().format($S('longDate'));
  $('time').innerHTML = new Date().format($S('formatTime'));
}

function populatePluginsList() {
  
  var ul = $('pluginList');
  ul.innerHTML = '';
  
  var j=0;
  for(var i in Lock_plugins) {
    
    if(typeof Lock_plugins[i] != 'object' || typeof Lock_plugins[i].desc == 'undefined')
      continue;
    
    var li = document.createElement('li');
    li.id = 'pluginList-'+String(i).replace(/([.:\s])/i,'-');
     var a = document.createElement('a');
     a.pName = i;
     if(Lock_plugins[i].defPlugin)
      a.className = 'defPlugin';
     Event.observe(a, 'click', function(){addPlugin(this.pName);});
     a.innerHTML = Lock_plugins[i].desc;
     a.href = '#null';
    li.appendChild(a);
    
    if(typeof Lock_plugins[i].creator != 'undefined') {
      li.appendChild(document.createTextNode(' - by '))
      var b = document.createElement('b');
      b.appendChild(document.createTextNode(Lock_plugins[i].creator));
      li.appendChild(b);
    }
    
    ul.appendChild(li);
    j++;
  }
  
  if(j == 0) {
    var li = document.createElement('li');
    li.className = 'emptyList';
    li.innerHTML = 'No plugins...';
    ul.appendChild(li);
  }
  
  Sortable.create('pluginBars',{scroll:'lockscreen', tag:'div', onChange: pluginsSorted, format: /^[^_\-](?:[A-Za-z0-9\_]*)[-_](.*)$/});
}

function deletePlugin(name) {
  
  if(name == 'clock') {
    $('default-clockBar').show();
    $('default-clockBar-toolTip').hide();
    $('default-clockBar-hint').hide();
  }
  
  if(name == 'weather')
    $('weather-toolTip').hide();
  
  if(name == 'cal')
    $('calendar-tollTip').hide();
  
  var sList = Sortable.sequence('pluginBars');
  
  if(name.indexOf('status:') == 0) {
    
    if(!((sList.include('status-rss') && name != 'status:rss') || (sList.include('status-mms') && name != 'status:mms') || (sList.include('status-silent') && name != 'status:silent')))
      $('statusNotifier-toolTip').hide();
  }
  
  if(name.indexOf(':') != -1)
    Sname = String(name).replace(/([.:\s])/i,'-');
  else
    Sname = name;
  
  if($(Sname+'-settings'))
    new Effect.Fade($(Sname+'-settings'), {duration: .5, afterFinish: function(e){e.element.remove();}});
  
  new Effect.Fade($('plugin-'+String(name).replace(/([.:\s])/i,'-')), {duration: .5, afterFinish: function(e){e.element.remove();Sortable.create('pluginBars',{scroll:'lockscreen', tag:'div', onChange: pluginsSorted, format: /^[^_\-](?:[A-Za-z0-9\_]*)[-_](.*)$/});}});
  new Effect.Appear($('pluginList-'+String(name).replace(/([.:\s])/i,'-')), {duration: 1.0});
}

function pluginsSorted() {
  var sList = Sortable.sequence('pluginBars');
  
  if(sList[0] == 'clock')
    $('default-clockBar-hint').hide();
  else if(sList.include('clock'))
    $('default-clockBar-hint').show();
  else
    $('default-clockBar-hint').hide();
}


var Plugin = function(params) {
  this.params = params;
  Lock_plugins[params.name] = this.params;
};

function addPlugin(name) {
  
  if(!Lock_plugins[name])
    return ;
  
  var sList = Sortable.sequence('pluginBars');
  
  if(sList.include(String(name).replace(/([.:\s])/i,'-')))
    return ;
  
  loadSettings(name);
  
  if(name == 'clock') {
    $('default-clockBar').hide();
    $('default-clockBar-toolTip').show();
    
    if(sList.length > 0)
      $('default-clockBar-hint').show();
  }
  
  if(name == 'weather')
    $('weather-toolTip').show();
  
  if(name.indexOf('status:') == 0)
    $('statusNotifier-toolTip').show();
  
  if(name == 'cal')
    $('calendar-tollTip').show();
  
  var plugin = Lock_plugins[name];
  
  var block = document.createElement('div');
  block.className = 'pluginBar'
  
  block.id = 'plugin-'+String(plugin.name).replace(/([.:\s])/i,'-');
  block.pName = plugin.name;
  block.style.display = 'none';
  
  if(plugin.header) {
    if(typeof plugin.header == 'object' && 'splice' in plugin.header && 'join' in plugin.header) {
      for(var i=0; i<plugin.header.length; i++) {
        var header = document.createElement('div');
        header.className = 'header';
        header.innerHTML = plugin.header[i];
        
        block.appendChild(header);
      }
    }
    else {
      var header = document.createElement('div');
      header.className = 'header';
      header.innerHTML = plugin.header;
      
      block.appendChild(header);
    } 
  }
  
  if(plugin.summary) {
    if(typeof plugin.summary == 'object' && 'splice' in plugin.summary && 'join' in plugin.summary) {
      for(var i=0; i<plugin.summary.length; i++) {
        var summary = document.createElement('div');
        summary.className = 'summary';
        summary.innerHTML = plugin.summary[i];
        
        block.appendChild(summary);
      }
    }
    else {
      var summary = document.createElement('div');
      summary.className = 'summary';
      summary.innerHTML = plugin.summary;
      
      block.appendChild(summary);
    } 
  }
  
  if(plugin.location) {
    if(typeof plugin.location == 'object' && 'splice' in plugin.location && 'join' in plugin.location) {
      for(var i=0; i<plugin.location.length; i++) {
        var location = document.createElement('div');
        location.className = 'location';
        location.innerHTML = plugin.location[i];
        
        block.appendChild(location);
      }
    }
    else {
      var location = document.createElement('div');
      location.className = 'location';
      location.innerHTML = plugin.location;
      
      block.appendChild(location);
    }
  }
  
  if(plugin.custom) {
    var customs = document.createElement('div');
    customs.className = 'customs';
    
    if(typeof plugin.custom == 'object' && 'splice' in plugin.custom && 'join' in plugin.custom) {
      for(var i=0; i<plugin.custom.length; i++) {
        var custom = document.createElement((plugin.custom[i].tagName || 'div'));
        custom.className = 'custom '+(plugin.custom[i].className || '');
        custom.innerHTML = (plugin.custom[i].content || '');
        
        customs.appendChild(custom);
      }
    }
    else {
      var custom = document.createElement((plugin.custom.tagName || 'div'));
      custom.className = 'custom '+(plugin.custom.className || '');
      custom.innerHTML = (plugin.custom.content || '');
      
      customs.appendChild(custom);
    }
    block.appendChild(customs);
  }
  
  
  
  var close = document.createElement('a');
  close.pName = name;
  Event.observe(close, 'click', function(){deletePlugin(this.pName);});
  close.style.display = 'block';
  close.style.padding = '7px';
  close.style.background = "url('imgs/MenuCloseButton.png') no-repeat center 1px";
  
  block.appendChild(close);
  
  new Effect.Appear($('pluginBars').appendChild(block), {duration: 1.0});
  new Effect.Fade($('pluginList-'+String(plugin.name).replace(/([.:\s])/i,'-')), {duration: .5});
  Sortable.create('pluginBars',{scroll:'lockscreen', tag:'div', onChange: pluginsSorted, format: /^[^_\-](?:[A-Za-z0-9\_]*)[-_](.*)$/});
}

function generate() {
  sList = Sortable.sequence('pluginBars');
  
  if(sList.length == 0) {
    if(!confirm("You didn't add any plugin. Do you want to generate the general settings.js file anyway ?\r\n(Click on OK to generate the file)"))
      return ;
  }
  
  this.disabled = true;
  this.value = 'Generating files...';
  $('settings').request({method: 'post', parameters: {sList: [sList]}, evalJSON: true, onSuccess: generated});
}


function generated(req) {
  this.disabled = false;
  this.value = 'Generate';
  
  if(!req.responseJSON) {
    alert("Unknown error!\r\n\r\nPage content:\r\n"+req.responseText);
    return ;
  }
  if(req.responseJSON.error) {
    if(req.responseJSON.allDef) {
      sList = Sortable.sequence('pluginBars');
      
      if(sList.length != 0)
        alert("You didn't change any default setting. To activate these plugins and change their order edit \"Private/settings.js\" and change \"plugins: [...],\" to :\r\nplugins: ['"+sList.join("','")+"'],");
      else
        alert('You didn\'t change anything and didn\'t add any plugin !');
      
      return ;
    }
    
    alert("Unknown error!");
  }
  else if(req.responseJSON.UID)
    document.location.href = '?down&id='+req.responseJSON.UID;
}



























  Date.prototype.format = function(format) {
		var returnStr = '';
		var replace = Date.replaceChars;
		for (var i = 0; i < format.length; i++) {
			var curChar = format.charAt(i);
			if (replace[curChar])
				returnStr += replace[curChar].call(this);
			else
				returnStr += curChar;
		}
		return returnStr;
	};
	
	Date.prototype.isDifferentDay = function(date2) {
		return (this.getDate() != date2.getDate() ||
			this.getMonth() != date2.getMonth() ||
			this.getFullYear() != date2.getFullYear());
	};
	
	Date.prototype.isToday = function()	{
		return !this.isDifferentDay(new Date());
	};

	Date.prototype.isTomorrow = function() {
		today = new Date ();
		return !this.isDifferentDay(new Date(today.getTime() + 24*60*60*1000));
	};

	Date.prototype.isWithinDays = function(duration)
	{
		today = new Date ();
		temp = new Date ();
		temp.setTime(today.getTime() + duration*24*60*60*1000);
		enddate = new Date();
		enddate.setDate(temp.getDate());
		enddate.setMonth(temp.getMonth());
		enddate.setFullYear(temp.getFullYear());
		enddate.setHours(23);
		enddate.setMinutes(59);
		enddate.setSeconds(59);
		
		return enddate.getTime() > this.getTime();
	};
	
	Date.replaceChars = {
	  shortMonths: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],
    longMonths: ["January","February","March","April","May","June","July","August","September","October","November","December"],
    shortDays: ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],
    longDays: ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
		// Day
		d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
		D: function() { return $L(Date.replaceChars.shortDays[this.getDay()]); },
		j: function() { return this.getDate(); },
		l: function() { return $L(Date.replaceChars.longDays[this.getDay()]); },
		N: function() { return this.getDay() + 1; },
		S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
		w: function() { return this.getDay(); },
		z: function() { return "Not Yet Supported"; },
		// Week
		W: function() { return "Not Yet Supported"; },
		// Month
		F: function() { return $L(Date.replaceChars.longMonths[this.getMonth()]); },
		m: function() { return (this.getMonth() < 11 ? '0' : '') + (this.getMonth() + 1); },
		M: function() { return $L(Date.replaceChars.shortMonths[this.getMonth()]); },
		n: function() { return this.getMonth() + 1; },
		t: function() { return "Not Yet Supported"; },
		// Year
		L: function() { return "Not Yet Supported"; },
		o: function() { return "Not Supported"; },
		Y: function() { return this.getFullYear(); },
		y: function() { return ('' + this.getFullYear()).substr(2); },
		// Time
		a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
		A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
		B: function() { return "Not Yet Supported"; },
		g: function() { return this.getHours() == 0 ? 12 : (this.getHours() > 12 ? this.getHours() - 12 : this.getHours()); },
		G: function() { return this.getHours(); },
		h: function() { return (this.getHours() < 10 || (12 < this.getHours() < 22) ? '0' : '') + (this.getHours() < 10 ? this.getHours() + 1 : this.getHours() - 12); },
		H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
		i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
		s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
		// Timezone
		e: function() { return "Not Yet Supported"; },
		I: function() { return "Not Supported"; },
		O: function() { return (this.getTimezoneOffset() < 0 ? '-' : '+') + (this.getTimezoneOffset() / 60 < 10 ? '0' : '') + (this.getTimezoneOffset() / 60) + '00'; },
		T: function() { return "Not Yet Supported"; },
		Z: function() { return this.getTimezoneOffset() * 60; },
		// Full Date/Time
		c: function() { return "Not Yet Supported"; },
		r: function() { return this.toString(); },
		U: function() { return this.getTime() / 1000; }
	}
	
	var Language = function(locale) {
    this.locale = locale;
    
    this.strings = [];
    
    this.symbols = [];
    
    this.setString = function(originalString, translated) {
      Lock_languages[this.locale].strings[originalString] = translated;
    };
    
    this.setSymbol = function(symbolDescription, symbol) {
      Lock_languages[this.locale].symbols[symbolDescription] = symbol;
    };
    
    Lock_languages[locale] = this;
  };
  
  function $L(str) {
    
    if((Lock_languages[Lock_language]) && (Lock_languages[Lock_language].strings[str]))
      return Lock_languages[Lock_language].strings[str];
    else if((Lock_languages[Lock_language.substring(0,2)]) && (Lock_languages[Lock_language.substring(0,2)].strings[str]))
      return Lock_languages[Lock_language.substring(0,2)].strings[str];
    else if((Lock_languages['en']) && (Lock_languages['en'].strings[str]))
      return Lock_languages['en'].strings[str];
    else
      return str;
  }
  
  function $S(str) {
    
    if((Lock_languages[Lock_language]) && (Lock_languages[Lock_language].symbols[str]))
      return Lock_languages[Lock_language].symbols[str];
    else if((Lock_languages[Lock_language.substring(0,2)]) && (Lock_languages[Lock_language.substring(0,2)].symbols[str]))
      return Lock_languages[Lock_language.substring(0,2)].symbols[str];
    else if((Lock_languages['en']) && (Lock_languages['en'].symbols[str]))
      return Lock_languages['en'].symbols[str];
    else
      return str;
  }
  

setLang('default');
loadPlugins();

new Event.observe(window, 'load', pageLoad);

