/*
* CssSwitcher 0.0.1
* Copyright (c) 2010 Yousuke Mizuno (www.thingslabo.com)
* $Date: 10.08.11 22:40:37 $
* $Rev: 004 $
* Dual licensed under the MIT and GPL licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
*/

if (typeof CssSwitcher == 'undefined') {
  var CssSwitcher = {};
 // Settings
  CssSwitcher.cssPath = "http://blog.thingslabo.com/css/"; // http://domain/path/to/css/
  CssSwitcher.idList = [ 'CssSize', 'CssLayout', 'CssColor', 'tag', 'parts' ]; // List up id attribute of 'stylesheet' rel attribute
  // Cookie Settings
  CssSwitcher.domain = "";
  CssSwitcher.path = "/";
  CssSwitcher.expires = 7; // days or a Date object Wdy, DD-Mon-YYYY HH:MM:SS GMT (ex. Fri, 01-Dec-2010 20:40:03 GMT)
  CssSwitcher.secure = 0; // 0 or 1
}

CssSwitcher.change = function (json) {
	for (var i=0; i<json.length; i++){
		var $ = document.getElementById(json[i].id);
		if ($ && json[i].theme) {
			$.href = CssSwitcher.cssPath + json[i].theme + ".css";
		}
	}

	var cookieVal = [];
	for (var i=0; i<CssSwitcher.idList.length; i++) {
		var match_id;
		for (var j=0; j<json.length; j++) {
			if (CssSwitcher.idList[i] == json[j].id) {
				cookieVal.push(["{'id':'", json[j].id, "'\,'theme':'", json[j].theme, "'}"].join(''));
				match_id = json[j].id;
				break;
			}
		}

		for (var j=0; j<CssSwitcher.json.length; j++) {
			if (CssSwitcher.idList[i] == CssSwitcher.json[j].id && CssSwitcher.idList[i] != match_id) {
				cookieVal.push(["{'id':'", CssSwitcher.json[j].id, "'\,'theme':'", CssSwitcher.json[j].theme, "'}"].join(''));
			}
		}
	}

	var expires;
	if (typeof CssSwitcher.expires == 'number') {
		var date = new Date();
		date.setTime(date.getTime() + (CssSwitcher.expires * 24 * 60 * 60 * 1000) );
		expires = ';expires=' + date.toUTCString();
	}
	else {
		expires = ';expires=' + CssSwitcher.expires;
	}
	var path = CssSwitcher.path ? '; path=' + CssSwitcher.path : '';
	var domain = CssSwitcher.domain ? '; domain=' + CssSwitcher.domain : '';
	var secure = CssSwitcher.secure ? '; secure' : '';

	document.cookie = ['CssSwitcher=', encodeURIComponent('['+cookieVal+']'), expires, path, domain, secure].join('');
	CssSwitcher.getJSON();
}

CssSwitcher.getJSON = function () {
	var cookieKey = "CssSwitcher=";
	var cookies = document.cookie + ";";
	var start = cookies.indexOf(cookieKey);
	if (start != -1) {
		var end = cookies.indexOf(";",start);
		var value = decodeURIComponent(cookies.substring(start + cookieKey.length, end));
		CssSwitcher.json = eval(value);
	}
	else {
		CssSwitcher.json = eval([{}]);
	}
}

CssSwitcher.init = function () {
	CssSwitcher.getJSON();
	CssSwitcher.change(CssSwitcher.json);
}

CssSwitcher.init();


