


var params = false;

jQuery.query = function(s) {
	var r = {};
	if (s) {
			var q = s.substring(s.indexOf('?') + 1); // remove everything up to the ?
			q = q.replace(/\&$/, ''); // remove the trailing &
			jQuery.each(q.split('&'), function() {
					var splitted = this.split('=');
					var key = splitted[0];
					var val = splitted[1];
					// convert numbers
					if (/^[0-9.]+$/.test(val)) val = parseFloat(val);
					// convert booleans
					if (val == 'true') val = true;
					if (val == 'false') val = false;
					// ignore empty values
					if (typeof val == 'number' || typeof val == 'boolean' || val.length > 0) r[key] = val;
			});
	}
	return r;
};


function getStyle(el, prop) {
  if (document.defaultView && document.defaultView.getComputedStyle) {
    return document.defaultView.getComputedStyle(el, null)[prop];
  } else if (el.currentStyle) {
    return el.currentStyle[prop];
  } else {
    return el.style[prop];
  }
}

var Blip = {
	speed : 300,
	lag: 5,
	timer: false,
	rotationWatcher: false,
	msg: [],
	msgHistory: [],
	repeatSpec: 100,
	offset: 0,
	speeds: [150,300,400,500,750,1200],
	uiState: 'form',
	string: null,
	flicks: [],
	debugMode: false,
	orient: false,
	timer2: false,
	animation: "shake,fade",
	accelTimer: false,
	currentWidth: 0,
	currentHeight: 0,
	backgroundColor: '#000000',
	foregroundColor: '#ffffff',
	colorMode: 'lod',
	emoticons: {},
	isNativeApp: false,
	db: false,
	lastx: false,
	customMsg: false,
	query: {
			phrase: '',
			duration: 500,
			repeat: 8
	},
	saves: []
}

Blip.emoticons = {
	":-)": {name: "smiley", src: "happy300.png"},
	"(V)": {name: "heart", src:"heart300.png"},
	"(v)":  {name: "heart", src:"love300.png"},
	":-(":  {name: "heart", src:"sad300.png"},
	":->":  {name: "Super Happy", src:"superhappy300.png"},
	";-)":  {name: "Cool", src:"cool300.png"},
	"<iB>": {name: "iBlipper", src:"splash.gif"}
			
	
}

Blip.debugMsg =  function(msg, level) {
	if(Blip.debugMode) console.log(msg);
}



Blip.setOpt = function(val, ele) {
	var matched = false;
	Blip.debugMsg("Setting opt for " + val + " to " + ele.nodeName);
	var curOptions = ele.options;
	for(var i = 0; i < curOptions.length; i++) {
		if(curOptions[i].value == val) {
			curOptions[i].selected = true;
			matched = true;
		} else {
			curOptions[i].selected = false;
		}
	}
}
/*
Blip.fetchInfoPanel() {
	jquery.ajax(
}*/


Blip.init = function(first) {
	this.string = '';
	
	Blip.debugMsg("Starting with " + this.string + " at " + this.query.duration + ' ' + this.animation);
	
	
	if(first) { 
		$(".colorBox").addTouch();

		if(this.isNativeApp) {
			$("#logolink").attr("href", "#");
			Blip.sizeOrientation();
			$("#bookmarkLink").click(Blip.saveBlip);
			$("#bookmarkLink").val("Save Blip");
	} else {
			Blip.updateOrientation();
			$("#bookmarkLink").click(Blip.bookmarkLink);
		}
	
		if(this.isNativeApp) this.db = new MagicPrefs("iblipper", this.dbReady)
		
		document.getElementById("display").addEventListener("touchstart", this.flickStart, false);
		document.getElementById("display").addEventListener("touchend", this.flickEnd, false);
		document.getElementById("display").addEventListener("touchmove", this.flickMove, false);
		document.getElementById("display").addEventListener("mousedown", this.flickStart, false);
		document.getElementById("display").addEventListener("mouseup", this.flickEnd, false);
		
		if(!Blip.isNativeApp) document.getElementById("display").addEventListener("click", this.clickToggle, false);
		
		$("select").blur(function() {window.scrollTo(0,1);},false);
		this.updateLayout();
	  if(!this.isNativeApp || !location.search.length && $.cookie("latest") ) {
				var savedSettings =$.evalJSON( $.cookie("latest"));			
		}

	if(savedSettings) {
			Blip.debugMsg("Restoring from cookie");
			Blip.animation = savedSettings.animation;
			Blip.speed = savedSettings.speed;
			Blip.query = savedSettings.query;
			Blip.duration = savedSettings.duration;
			Blip.foregroundColor = savedSettings.foregroundColor;
			Blip.backgroundColor = savedSettings.backgroundColor;
			Blip.parseMsg();
		}
		if(!this.isNativeApp) {
			var params = $.query(location.search);
			
			if(typeof(params["q"]) != 'undefined') this.query.phrase = params["q"];
			if(typeof(params["a"]) != 'undefined') {
				this.animation = unescape(decodeURI(params["a"]));
			}
			if(typeof(params["r"]) != 'undefined') {
				this.query.repeat = params["r"]; // repeat count
				this.repeatSpec = this.query.repeat;
				
			}
			if(typeof(params["d"]) != 'undefined') {
				this.query.duration = params["d"]; // duration per word
				this.speed = params["d"];
				this.duration =  params["d"];
			}
			Blip.parseMsg();
		}	

		if(this.query.duration && !isNaN(parseInt(this.query.duration))) {
			this.setOpt(this.query.duration, $("#cp_d")[0]);
			this.setOpt(this.animation, $("#cp_a")[0]);		
		} 
	}
	// END FIRST RUN SETUP

	
	if(this.query.phrase && this.query.phrase.length ) {
		window.scrollTo(0,1) ;
		$("#startform").css("display","none");
		$("#display").css("display","");
		this.string = unescape(this.query.phrase);
		document.title ="iBlipper: " +  " :: " + this.string;
		if(this.msg.indexOf("%20") > -1) {
		    this.msg = decodeURI(this.msg);
		}
		this.msg = this.string.split(new RegExp( "[+ ]{1}", "g" ));
		this.parseMsg();
		$("#q").attr("value", this.msg.join(" "));
		if(Blip.orient == 'portrait') {
				Blip.toggleControlPanel();
		} else {
			Blip.animate();
		}
	} else {
		Blip.debugMsg("No settings, showing starter form");
		$("#startform").css('display','');
	}
}

Blip.prepTouch = function() {}

Blip.parseMsg = function () {
	this.blips = [];
	Blip.debugMsg("Parsing Msg from " + Blip.msg, 9);
	//Blip.query.phrase = Blip.msg;
	/* var brand = Blip.interpWord("<iB>");
	this.blips.push( { 
					displayWord: brand.word || word,
					duration: 300,
					animation: "fade,",
					lag: 50
					} ); */
	for(var i=0;i<Blip.msg.length;i++) {
		// displayWord 
		// duration
		// animation
		// lag
		var word = this.msg[i];
		
		var animSpec = this.interpWord(word);
		
		this.blips.push( { 
			displayWord: animSpec.word || word,
			duration: animSpec.duration,
			animation: animSpec.animation,
			lag: animSpec.lag,
		} );
		
	}

	Blip.debugMsg(this.blips);
};

Blip.interpWord = function(word) {
	var animSpec = {};
	Blip.debugMsg("Setting speed from " + this.speed);
	animSpec.duration = this.speed;
	animSpec.lag = this.lag;
	animSpec.animation = this.animation;
	animSpec.word = word;
	
	if(typeof(Blip.emoticons[word]) != 'undefined') {
			animSpec.word = "<img src='" + Blip.emoticons[word].src + "' style='position:absolute;top:0;left:90;' align='center' ";
			if(!Blip.isNativeApp) animSpec.word += " height='280'";
			animSpec.word += "/>";
	}
	if(word.match(/[.,;:]$/)) {
		animSpec.lag *= 2;
	} 	
	
	// @...@
	if(word.match(/^@.*@$/)) {
		animSpec.word = word.substring(1,word.length-1);
		animSpec.animation = 'wiggle,fade';
	}
	// Exclamation
	if(word.match(/.*!$/)) {
		animSpec.animation = 'wobble,zoomout';
	}
	//  Comma
	if(word.match(/.*,$/)) {
		animSpec.animation = 'topbounce,fade';
	}
	
	// Period
	if(word.match(/.*\.$/)) {
		animSpec.animation = 'zoomout,shake';
	}
	
	// _..._
	if(word.match(/^_.*_$/)) {
		animSpec.speed += (this.speed/2);
		animSpec.word = word.substring(1,word.length-1);
	}
	// __..__ Doesnt work
	if(word.match(/^_._*__$/)) {
		animSpec.speed += (this.speed);
		animSpec.word = word.substring(2,word.length-2);
	}
    // #...# s
	if(word.match(/^#.*#$/)) {
		animSpec.animation = 'topbounce,fade';
		animSpec.word = word.substring(1,word.length-1);
	} /* */
    // "..." s
	if(word.match(/^".*"$/)) {
			animSpec.speed += (this.speed);
			animSpec.word = word.substring(1,word.length-1);
	} /* */

return animSpec;
};

Blip.animate = function() {
	
	var savedSettings = {
		speed:Blip.speed,
		repeatSpec: Blip.repeatSpec,
		animation: Blip.animation,
		query: Blip.query,
		backgroundColor: Blip.backgroundColor,
		foregroundColor: Blip.foregroundColor
		
	}
	if(!Blip.isNativeApp) {
		$.cookie("latest", $.compactJSON(savedSettings),  { path: '/', expires: 50 });
	}
  var sheight = window.innerHeight;
	var swidth = window.innerWidth;
	var theight, twidth;
	var node = document.createElement("div");
	var word = Blip.msg[Blip.offset];
	var indent = 0;
	var offset = Blip.offset;
	var curBlip = Blip.blips[this.offset];
	var msg =this.msg; // NUke MSG
	if(offset >= (Blip.blips.length)) {
		
		if(Blip.query.repeat <= 0) {
			$("#startform").css("display","");
			$("#display").css("display","none");
			window.scrollTo(0,1) ;
			 
			Blip.cancelTimer();
			Blip.synchControls();
			Blip.goHome();
		} else {
			Blip.query.repeat--;
			Blip.offset = 0;
			$("#display").html('&nbsp;&nbsp;');
			this.timer = window.setTimeout(function(){Blip.animate()}, 1000); //this.speed*2); was too slow in some cases
		}
	} else {
	  this.uiState = 'blipping';
		if((this.offset == 0) && !this.timer) {	
			this.offset = 0;
			this.timer = window.setTimeout(function(){Blip.animate()}, this.speed);
			window.scrollTo(0,1) ;
		} else {
			$("#t" + (offset-1)).remove();
			node.innerHTML = curBlip.displayWord; //this.msg[offset]; // Should be curBlip.word

			twidth = parseInt(node.offsetWidth);
			theight = parseInt(node.offsetHeight);
			node.id = 't' + offset;
		// TODO: FIgure out formula for widths based upon character len of word
			var lenBySize = [318,310,260,200,150,133,105,90,90,90,90,70,60,50,40,38,38,38,36,34,33,32,31,30,29,29,28,28,28,28,27,27,27,27,27,26];
			
		
			if(this.currentWidth > 490) {
				for(var z = 0; z < lenBySize.length; z++) {
					lenBySize[z] = (this.currentHeight / 490) * lenBySize[z];
				}
			}
			
			var wordlen = curBlip.displayWord.length;
			if(wordlen < lenBySize.length) {
				node.style.fontSize = lenBySize[wordlen -1] + "px";
				//node.style.paddingTop = (this.currentHeight - (lenBySize[wordlen - 1]*2)*.4)/2 + 'px'; 
				//node.style.paddingTop =  (this.currentHeight - (lenBySize[wordlen - 1]))/2.1 + 'px';
				indent = (Blip.currentWidth - (lenBySize[wordlen - 1]*.6*wordlen))/2
		
				if(indent > 0) {
					node.style.paddingLeft =  indent + "px";
					node.style.paddingRight=  indent + "px";
				}			

			} else { // If it's a really long word -- we should make it shorter
				//node.style.paddingTop =   (Blip.currentHeight - (lenBySize[wordlen - 1]*0.6*wordlen))/2 + 'px';
				//node.style.paddingTop =  (Blip.currentHeight - (lenBySize[wordlen - 1]*0.6*wordlen))/2 + 'px';
				node.style.fontSize = lenBySize[lenBySize.length -1] + "px";
			}
			if( curBlip.displayWord.indexOf('<img') > -1) {
				//node.innerHTML = " " + node.innerHTML + " ";
				//window.scrollTo(0,$("#display").offset().top + 50);
				//node.style.paddingTop = 10  + 'px';
				//node.style.paddingBottom = 10 + 'px';
				node.style.paddingLeft = '90px';
				window.scrollTo(0,1) ;
			}

			if(curBlip.duration ) {
				node.style.webkitAnimationDuration = curBlip.duration/1000 +"s,"  + curBlip.duration/1000 +"s"; // TODO: Move this to animSpec object
				node.style.webkitAnimationName = curBlip.animation;
			} else {
				node.style.webkitAnimationDuration = curBlip.duration/1000 +"s,"; // TODO: Move this to animSpec object
				node.style.webkitAnimationName = curBlip.animation.split(",")[0];
			}
			node.style.display='none';
			document.getElementById("display").appendChild(node);
			$( '#t' + offset).css("margin-top",   ( Blip.currentHeight - $( '#t' + offset).innerHeight())/2 + 'px');
			node.style.display = '';							
			window.setTimeout(function(){ $('#t' + offset).hide(); }, curBlip.duration);
			Blip.debugMsg(curBlip.duration + " vs lag " + curBlip.lag)

			if(Blip.uiState != 'paused') {
					Blip.timer = window.setTimeout(function(){Blip.animate()}, parseInt(curBlip.duration) + parseInt(curBlip.lag));
				//alert(this.timer + " " + " with offset " + offset);
				Blip.offset++;
			}
		}
	}
}

Blip.tweakInterval = function(msg) {
	var delay = Blip.speed;
	delay = delay  + (10 * (this.msg.length -4));
	if(this.msg.indexOf(".") > -1 || this.msg.indexOf("?") > -1) {
		delay = delay + this.speed*2/3;
	}
	return delay;
}


// Update textarea from select
Blip.doSelect = function() {
	Blip.debugMsg("Doing select");
 	var lines = $("#lines")[0];
	Blip.debugMsg(theMsg + " at " +lines.selectedIndex);
	var theMsg = lines.options[lines.selectedIndex].value;
	$('#q').val( theMsg);
	Blip.msg = theMsg;
	Blip.query.phrase = theMsg;
	Blip.parseMsg();
}

Blip.updateSelectedMsg = function () {
	Blip.debugMsg("Updating selected msg");
	var lines = $("#lines")[0];
	theMsg = lines.options[lines.selectedIndex].value;
	var newMsg = $('#q').val();
	var opt;
	Blip.debugMsg("Considering adding " + theMsg + " to " + newMsg.length);
	if(newMsg != theMsg && newMsg.length)  {
		
			opt = "<option value='" + newMsg + "'>" + newMsg + "</option>"
			 $("#lines").html(opt +  $("#lines").html()); 
			 $("#cp_msg").html(opt +  $("#cp_msg").html()); 
			 
			// TODO ESCAPE QUOTES			
			lines.selectedIndex = 0;
	}
}


Blip.toggleControlPanel = function() {
	var cp = $("#controlPanel");
	window.clearTimeout(this.timer);
	
	if(cp.css("display") == 'none' && this.orient=='portrait') {
	  Blip.synchControls();  
		window.clearTimeout(this.timer);
		Blip.toggleDisplayState('controlPanel');
		
		window.scrollTo(0,1) ;
		try {
	  	if(!Blip.isNativeApp && typeof(pageTracker) != 'undefined') pageTracker._trackEvent("Mode", "ControlPanel", this.animation);
		} catch(err) {
			// error logging
		}
		Blip.uiState = 'controlpanel';
		if(Blip.customMsg) {
			if(Blip.isNativeApp) $("#bookmarkLink").attr("disabled", false);
		} else {
			if(Blip.isNativeApp) $("#bookmarkLink").attr("disabled", true);		
		}
		if(!Blip.accelTimer && Blip.isNativeApp) watchAccel(); //Blip.watchForShake();

		Blip.updateLayout();
		
	} else {
	    
		cp.css("display","none");
		Blip.parseMsg();
		Blip.timer = window.setTimeout(function(){Blip.animate()}, this.speed / 2);
		Blip.uiState = false;
	}
}


Blip.start = function() {
	Blip.debugMsg("Starting with " + $("#lines") + " of val " + $("#lines").val());
	Blip.synchControls();
	Blip.query.phrase = $("#q").val();
	Blip.debugMsg("Starting with " + this.string + " at " + this.query.duration + ' ' + this.animation);
	Blip.uiState = 'reinit';
	Blip.parseMsg ();
	Blip.debugMsg("Msg Parsed");
	Blip.debugMsg("Starting with " + this.string + " at " + this.query.duration + ' ' + this.animation);
	$("#startform").css('display','none');
	$("#controlPanel").css("display","none");
	Blip.debugMsg("Initing");
	Blip.init(false);
}

Blip.goHome = function () {
		Blip.offset = 0;
		Blip.msg = [];
		//Blip.debugMsg("repeat is " + Blip.repeat);
		Blip.query.repeat = this.repeatSpec; 
		Blip.cancelTimer();
		Blip.debugMsg("Going home.");
		this.uiState = 'reinit';
		Blip.toggleDisplayState('form')
		
}

// Not yet used
Blip.toggleDisplayState = function(mode) {
	if(mode == 'form') {
		$("#display").html('&nbsp;&nbsp;');
		$("#display").css("display","none");
		$("#controlPanel").css("display","none");
		
		$("#startform").css("display","");
	}
	if(mode == 'controlPanel') {
		$("#controlPanel").css("display","");
		$("#display").css("display","none");
		$("#startform").css("display","none");
	}
	if(mode = 'display') {
		
	}
	
}

Blip.restart = function() {
	Blip.offset = 0;
	$("#controlPanel").css("display","none");
	$("#startform").css("display","none");
	
	Blip.msg = [];
	Blip.cancelTimer();
	Blip.uiState = 'reinit';
	$("#display").html('&nbsp;&nbsp;');
	Blip.init(false);
	
}

Blip.newMessage = function() {
    document.location = 'index.html?r='+this.query.repeat+'&d='+this.query.duration;
}

Blip.cancelTimer = function() {
	if(Blip.timer) {
		window.clearTimeout(Blip.timer);
		this.timer = false;
	}
}

Blip.bookmarkLink = function () {
	if(!Blip.isNativeApp) document.location = 'http://' + document.location.hostname + "/" +document.location.pathname + '?a=' + this.animation + '&d=' + this.query.duration + '&r=' + this.query.repeat + '&q=' + encodeURIComponent(this.query.phrase);
}


Blip.updateOrientation = function ()
{
	var orientation=window.orientation;
	switch(orientation)
	{
	
		case 0:
				$("body").removeClass("landscapeLeft");
				$("body").removeClass("landscapeRight");			
				$("body").addClass("portrait");
				$("body").attr("orient", "portrait");
				Blip.orient = 'portrait';
				
				break;	
				
		case 90:
				$("body").removeClass("portrait");
				$("body").removeClass("landscapeRight");			
				$("body").addClass("landscapeLeft");
				$("body").attr("orient", "landscapeLeft");
			Blip.orient = 'landscapeLeft';
				break;
		
		case -90:	
				$("body").removeClass("landscapeLeft");
				$("body").removeClass("portrait");			
				$("body").addClass("landscapeRight");	
				$("body").attr("orient", "landscapeRight");
				Blip.orient = 'landscapeRight';
				break;
	}
	Blip.updateLayout();

}

Blip.sizeOrientation = function() {
	if (window.innerWidth != Blip.currentWidth) { 
		Blip.currentWidth = window.innerWidth;
		Blip.currentHeight = window.innerHeight;
		var orient = (Blip.currentWidth == 320) ? "portrait" : "landscapeLeft";
		Blip.debugMsg("Togging orient in legacy watcher to " + orient);
		if(Blip.orient != orient) {
			$("body").attr("orient", orient);
			Blip.orient = orient;
			//window.scrollTo(0, 1);
			Blip.updateLayout();
			
		}
	}
};

Blip.updateLayout = function() {
  Blip.debugMsg("Updating layout from " + this.uiState);
	this.currentWidth = window.innerWidth;
	this.currentHeight = window.innerHeight;
	if(this.orient == 'portrait') {
		Blip.debugMsg("Triggering control panel in orient watcher");
		if(this.uiState != 'controlpanel'  && this.uiState != 'form' && this.uiState != 'reinit') Blip.toggleControlPanel();	
	} else {
	// Landscape		
	
		if(this.uiState == 'controlpanel') {
			this.uiState = 'reinit';		
			Blip.debugMsg("Restarting");
			Blip.synchControls();
			Blip.restart();		
		}
		
	}
  window.scrollTo(0, 1);
};

Blip.flickStart = function(e) {
	//Blip.debugMsg("Flick started." + e.touches[0].pageX);
	if(e.touches) {
		var obj = { 'x': e.touches[0].pageX,  'y': e.touches[0].pageY } 
	} else {
		var obj = { 'x': e.pageX,  'y': e.pageY } 
	
	}
	
	Blip.flicks.push(obj);
}

Blip.flickEnd = function(e) {
	var direction;
	var offset =0;
	var delta;
	Blip.debugMsg("Flickend");
	
	if(typeof(e.pageY) == 'undefined') {
		
		
		var obj = { 'x': e.touches[0].pageX,  'y': e.touches[0].pageY };
		Blip.flicks.push(obj);
		if(Blip.flicks.length) {
				delta =   Blip.flicks[Blip.flicks.length-1].x -  Blip.flicks[0].x;
				if(delta > 10) { direction = -1  }else {direction = 1};
		}
	} else {
				if(Blip.flicks.length) {
					delta =   Blip.flicks[Blip.flicks.length-1].x -  Blip.flicks[0].x;
					if(delta > 10) { direction = -1  }else {direction = 1};
			}
	}
	
	while(Blip.speeds[offset] < Blip.speed) {
		
		offset++;
		
	}
	var newSpeed;
	newSpeed =  Blip.speeds[offset  + direction];
	
	if(typeof(newSpeed) != 'undefined') {
			if(Blip.isNativeApp) {
			if(direction > 0) {
							navigator.notification.vibrate(25);
							navigator.notification.vibrate(0);
	
			} else {
							 navigator.notification.vibrate(0);
							navigator.notification.vibrate(25);
			
			}
		}
		Blip.speed =newSpeed;
		Blip.parseMsg();
		Blip.query.duration = Blip.speed;
		// Synch during gesture
		Blip.synchControls();
		
	} else {
		Blip.debugMsg("Tried to alter speed " + offset + " in " + direction);
	}
	Blip.debugMsg("ALTERED SPEED to " + Blip.speed);
	Blip.flicks = [];
}

Blip.flickMove = function(e) {
	
	var obj = { 'x': e.touches[0].pageX,  'y': e.touches[0].pageY } 
	Blip.flicks.push(obj);
	Blip.debugMsg(Blip.flicks[0].y-Blip.flicks[Blip.flicks.length-1].y);
	
	if(Blip.uiState=='blipping' || Bip.isNativeApp) {	//Blip.debugMode && 
				e.preventDefault();
	}
}

Blip.clickToggle = function(e) {
	
	
}


Blip.synchControls = function() {
	this.setOpt(this.speed, $("#cp_d")[0]);
	this.setOpt(this.animation, $("#cp_a")[0]);
	this.setOpt(this.repeatSpec, $("#cp_r")[0]);
	document.body.style.backgroundColor = Blip.backgroundColor;
	document.body.style.fontColor = Blip.foregroundColor;
	// kicks in duration 
	Blip.parseMsg();	
}

Blip.showCategory = function (category) {
	var catNode = $("#" + category);
	if(catNode.hasClass("collapsed")) {
		catNode.removeClass("collapsed");
	} else {
		catNode.addClass("collapsed");
	}
}

Blip.blipFromMenu = function (message, effect, speed, repeat) {
	$("#q").val(message);
	window.scrollTo(0,1);
	Blip.customMsg = false;
}

Blip.setCaretPosition = function(elemId, caretPos) {
    var elem = document.getElementById(elemId);
		elem.focus();
 		var range = elem.createTextRange();
		elem.collapse(true);
		elem.moveEnd('character', pos);
		elem.moveStart('character', pos);
		elem.select();
}


if(Blip.isNativeApp) {
	window.setInterval(Blip.sizeOrientation, 100);
} else {
	window.onorientationchange=Blip.updateOrientation;	
}

Blip.dbReady = function() {
	Blip.db.LoadSaveData(Blip.writeSaved);
	
}

Blip.writeSaved = function() {
	var category;
	var ablip;
	var content = '<a href="javascript:Blip.showCategory(\'custom\');" class="catlink">My Blips </a>';
	Blip.debugMsg(Blip.db.data.length);
		category = $("#greetings").clone();
		category.attr("id","custom");
		for(var i in Blip.db.data) {
			if(Blip.db.data[i].length) {
				Blip.saves.push(Blip.db.data[i]);
				ablip = $.evalJSON( Blip.db.data[i] );
					content += '<div class="msg" id="m' + i + '">';
					content += '<span style="float:right;background-color:#333;padding:4px;margin:3px 0px 3px 5px;"><a href="#" style="font-color:#fff;color:#fff;font-size:11px;"  onclick="Blip.clearSave(\'' + i + '\');">X</a></span>'
					content += '<a href="javascript:Blip.blipFromMenu(\'' + ablip.query.phrase + '\');">' + ablip.query.phrase + '</a>';
					content += '</div>' ;
				}
		}
		category.html(content);
		$("#greetings").before(category);
}

Blip.saveBlip = function() {
	var savedSettings = {
		speed:Blip.speed,
		repeatSpec: Blip.repeatSpec,
		animation: Blip.animation,
		query: Blip.query,
		foregroundColor: Blip.foregroundColor,
		backgroundColor: Blip.backgroundColor
	}
	
	Blip.db.SavePref(new Date().getTime(), $.toJSON(savedSettings));
	$("#custom").remove();
	Blip.customMsg = false;
	Blip.writeSaved();
	$("#bookmarkLink").attr("disabled", true);		
}

Blip.clearSave = function(id) {
	Blip.db.EraseItem(id);
	$("#m" + id).remove();
}

Blip.toggleColor = function(color, shade ) {
	var inverse = $("#dol").attr("checked");
	if(shade == 'light') {
			if(inverse) {
				document.body.style.backgroundColor = color;
				
			} else {
				document.body.style.color = color;
			}
	} else {
		if(inverse) {
				document.body.style.color = color;
		} else {
			document.body.style.backgroundColor = color;
		}
	}
	Blip.backgroundColor = document.body.style.backgroundColor;
	Blip.foregroundColor= document.body.style.color;
}

Blip.toggleColorPolarity = function() {
		Blip.debugMsg("Polarity " + document.body.style.color + " and " + document.body.style.backgroundColor + " with " + $("#dol").attr("checked") );
	var inverse = $("#dol").attr("checked");
	
		var temp=$("body").css("color");
		$("body").css("color", $("body").css("background-color"));
		$("body").css("background-color", temp);
		Blip.backgroundColor = $("body").css("background-color");
		Blip.foregroundColor= $("body").css("color");
		if(inverse) {
			Blip.colorMode = 'lod';
		} else {
			Blip.colorMode = 'dol';
		}
	
}

function watchAccel(a) {
	//debug.log("watchAccel");
	
	 var suc = function(a){
		 var delta = 0;
		// debug.log(" Got accel " + a);
		 if(Blip.lastx) {
			 delta = Blip.lastx - a.x;
			 debug.log(a.x + "__" + delta); // a.y + "___" + a.z);// The user has shaken their device. Do something	 
			 if (Math.abs(a.x) > 1.2 || (delta >= 1.2 || delta <= (0 - 1.2)))
			 {
				 Blip.shakeIt();
			 }
		 }
		 Blip.lastx = a.x;
	
	};
	//debug.log("suc defined");
	var fail = function(){};
	var opt = {};
	opt.frequency = 500;
	//alert( navigator.accelerometer.watchAcceleration);
	//navigator.accelerometer.getCurrentAcceleration(fail,fail);
	//debug.log("trying to create timer");
	try {
		
		Blip.accelTimer =  navigator.accelerometer.watchAcceleration(suc,fail,opt);
	} catch(err) { debug.log(" Erro creating timer " + err); }
	 //debug.log("\ntimer created");
}

Blip.shakeIt = function() {
	if(Blip.uiState == 'controlpanel') {
		var delay = document.getElementById("cp_d");
		var animation = document.getElementById("cp_a");
		
		
		console.log(delay.options[delay.selectedIndex].value);
		delay.selectedIndex = Math.round( Math.random()*(delay.options.length-1) );
		animation.selectedIndex = Math.round( Math.random()*(animation.options.length-1) );
		Blip.speed = delay.options[delay.selectedIndex].value;
		Blip.animation = animation.options[animation.selectedIndex].value;
		Blip.parseMsg();
		Blip.lastx = false;
		var darks = document.getElementById("darkpalette").getElementsByTagName("span");
		$(darks.item(Math.round(Math.random()*(darks.length-1) ))).click();
		var lights = document.getElementById("lightpalette").getElementsByTagName("span");
		$(lights.item(Math.round(Math.random()*(lights.length-1)))).click();																					 
		
	}
}

