//COSNTANTS
MOVNOTE = {};
MOVNOTE.fetchLimit = {
	"search" : 10,
	"trip" : 9,	
	"bookmark" : 10,		
	"track" : 10,
	"comment" : 20,	
	"response" : 5,		
	"follow" : 10,
	"note" : 6
}

MOVNOTE.url = {
	"host" : "http://www.movnote.com" 
}

MOVNOTE.common =  {
	 "message_id":"div#message"
}
Function.prototype.method = function(name, func) {
	this.prototype[name] = func;
	return this;
};

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"MNDefault":      "mmm dd yyyy HH:MM:ss",
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

var Controller = function() {
	
	var that = {}; 
	that._delegates = []; 
	
	that.add_delegate = function(del) {
		this._delegates.push(del);
	};
	
	that.run_delegate = function(name) {
		
		var len = this._delegates.length; 
		
		for (var j=0; j<len; j++) {
			var del = this._delegates[j];
			if (del.hasOwnProperty(name)) {
				var method = del[name]
				
				var args = []
				for (var i=1; i<arguments.length; i++) {
					args.push(arguments[i]);
				}
				method.apply(del, args);
			}
		}
	};
	return that;
};

var APIKEY_COOKIE_KEY = 'movnote_apikey'
var SECRET_COOKIE_KEY = 'movnote_secret'
var TOKEN_COOKIE_KEY = 'movnote_token'
var NICK_NAME_COOKIE_KEY = 'movnote_nickname'
var USER_ID_COOKIE_KEY = 'movnote_userid'
var PIC_COOKIE_KEY = 'movnote_userpic'
var LOCALE_COOKIE_KEY = 'django_language'

var MNUtil = function (){

	var add_zero = function (n) {
	    // Format integers to have at least two digits.
	    return n < 10 ? '0' + n : n;
	};
	
	var remove_zero = function (n) {
		return n.replace(/^0/, "");
	};

	return {
		trans : function(msg) {
			return MOVNOTE.messages[msg];
		}, 
		parse_latlng: function(str) {
			if (str != null) {
				var locs = str.split(','); 
				if (locs.length == 2)
				{
					var latlng = new google.maps.LatLng(parseFloat(locs[0]), parseFloat(locs[1]));
					return latlng;
				}
			}
			return null;
		},
		time_format_day_hour_minute_second : function(milliseconds) {
			
			seconds = milliseconds/1000;

			var days = Math.floor(seconds / 86400); 
			var remain = Math.floor(seconds % 86400); 
			var hours = Math.floor(remain / 3600);
			remain = Math.floor(remain % 3600); 
			var minutes = Math.floor(remain / 60);
			seconds =  Math.floor(remain % 60);
			
			return [days,hours,minutes,seconds];
		},
		date_tostring: function(dt, date_only){

			if (dt != null && dt != '') 
			{
				var str = dt.getFullYear()   + '-' +
	            add_zero(dt.getMonth() + 1) + '-' +
	            add_zero(dt.getDate()); 
	
				if (!date_only) {
					str += 'T' +
		            add_zero(dt.getHours())     + ':' +
		            add_zero(dt.getMinutes())   + ':' +
		            add_zero(dt.getSeconds()) + 'Z';
				}
				return str;
			}
			else
			{
				return '';
			}
		},
		
		combine_date_time: function(date_date, date_time) {

			if (date_date && date_time) {
				var dt = new Date(); 				
				dt.setFullYear(date_date.getFullYear());			
				dt.setMonth(date_date.getMonth());			
				dt.setDate(date_date.getDate());	
				dt.setHours(date_time.getHours());
				dt.setMinutes(date_time.getMinutes());					
				dt.setSeconds(date_time.getSeconds());	
				dt.setMilliseconds(0);										
				return dt;
			}else{
				return null;
			}
		},
		
		parse_date: function(str) {
			if (str) {
				var ary = str.split('T');
			
				if (ary.length == 2) {
					var date_part = ary[0];
					var time_part = ary[1]; 
			
					var dates = date_part.split('-'); 
					var times = time_part.split(':');
					if (dates.length == 3 &&
						(times.length >= 2 || times.length <= 3))
						{
							dt = new Date(); 
						
							var date = parseInt(remove_zero(dates[2]));
							if (date < 0 || date > 31)
								return null; 
								
							var month = parseInt(remove_zero(dates[1])) - 1;
							if (month < 0 || month > 12)
								return null; 
							
							var year = parseInt(dates[0]);
							if (year < 0 || year > 9999)
								return null;
 
							dt.setFullYear(year);								
							dt.setMonth(month);
							dt.setDate(date); 

						
							if (times.length == 3) {
								var sec_str = remove_zero(times[2]);
								sec_str = sec_str.substring(0, 2);
								var sec = parseInt(sec_str);
								if (sec < 0 || sec > 60)
									return null;
								dt.setSeconds(sec);
							}else {
								dt.setSeconds(0);
							}
							if (!times[1])
								return null; 
							var min = parseInt(remove_zero(times[1])); 
							if (min < 0 || min > 60)
								return null;
							
							if (!times[0])
								return null; 
							var hr = parseInt(remove_zero(times[0])); 
							if (hr < 0 || hr > 24)
								return null;

							dt.setMinutes(min);
							dt.setHours(hr);
							dt.setMilliseconds(0);
						
							return dt;
						}
				}
			}
			return null;
		}, 
		
		calculate_map_center_bounds: function(items) {
			
			var latsum = 0; 
			var lngsum = 0; 

			var len = items.length
			var withLocations = [];
			for (var j=0; j<len; j++) {
				var item = items[j]; 
				if (item.location) {
					var latlng = MNUtil.parse_latlng(item.location);
					latsum += latlng.lat(); 
					lngsum += latlng.lng(); 					
					withLocations.push(latlng);
				}
			}

			var count = withLocations.length;
			if (count > 0) {
				var latmean = latsum/count; 
				var lngmean = lngsum/count; 
				
				var latdiff = 0; 
				var lngdiff = 0; 
				for (var i=0; i<count; i++) {
					var latlng = withLocations[i]; 
					latdiff += (latlng.lat() - latmean)*(latlng.lat() - latmean);
					lngdiff += (latlng.lng() - lngmean)*(latlng.lng() - lngmean);
				}
				
				var latsd = Math.sqrt(latdiff/count); 
				var lngsd = Math.sqrt(lngdiff/count); 
				var center = new google.maps.LatLng(latmean, lngmean);
				
				var latdelta = latsd * 4;
				var lngdelta = lngsd * 4; 
				

				var bound_ne = new google.maps.LatLng(latmean + latdelta, lngmean + lngdelta);			
				var bound_sw = new google.maps.LatLng(latmean - latdelta, lngmean - lngdelta);					

				var bounds = new google.maps.LatLngBounds(bound_sw, bound_ne);
				return {bounds:bounds, center:center};
			}
			
			return null;
		}
	};
	
}();

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

var readCookie = function (name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
};

function eraseCookie(name) {
	createCookie(name,"",-1);
}

var MNRequest = function() {
	
	var _service_url = "/rest"; 
	var _entity = null;
	var _request_error = null; 
	var _request_success = null;
	var _object = null; 
	var _async = null;
	var _complete_fn = null;
	
	var load_success = function(data, object) {
		if (data.error) {
			if (_request_error)
				_request_error(data.error, object);
		}else {
			if (_request_success) {
				if (object) {
					_request_success(data, object);
				}else {
					_request_success(data);
				}
			}
		}
	};
	
	var load_error = function(status, err, object) {
		var error = {code:status, msg:err};
		if (_request_error)
			_request_error(error, object);
	};
	
	var encode = function(params) {
	
	    var pairs = [];
	    $.each(params, function(key, val) {
			if (val !== null && typeof val != 'undefined' && key != 'base64_data') {
				pairs.push(key + '=' + quote(val));
			}
	    });
	    pairs.sort();
	    return pairs.join('');	
	};
	var jsSHA = function(k,l){jsSHA.charSize=8;jsSHA.b64pad="";jsSHA.hexCase=0;var m=null;var o=function(a){var b=[];var c=(1<<jsSHA.charSize)-1;var d=a.length*jsSHA.charSize;for(var i=0;i<d;i+=jsSHA.charSize){b[i>>5]|=(a.charCodeAt(i/jsSHA.charSize)&c)<<(32-jsSHA.charSize-i%32)}return b};var p=function(a){var b=[];var c=a.length;for(var i=0;i<c;i+=2){var d=parseInt(a.substr(i,2),16);if(!isNaN(d)){b[i>>3]|=d<<(24-(4*(i%8)))}else{return"INVALID HEX STRING"}}return b};var q=null;var r=null;if("HEX"===l){if(0!==(k.length%2)){return"TEXT MUST BE IN BYTE INCREMENTS"}q=k.length*4;r=p(k)}else if(("ASCII"===l)||('undefined'===typeof(l))){q=k.length*jsSHA.charSize;r=o(k)}else{return"UNKNOWN TEXT INPUT TYPE"}var s=function(a){var b=jsSHA.hexCase?"0123456789ABCDEF":"0123456789abcdef";var c="";var d=a.length*4;for(var i=0;i<d;i++){c+=b.charAt((a[i>>2]>>((3-i%4)*8+4))&0xF)+b.charAt((a[i>>2]>>((3-i%4)*8))&0xF)}return c};var u=function(a){var b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var c="";var d=a.length*4;for(var i=0;i<d;i+=3){var e=(((a[i>>2]>>8*(3-i%4))&0xFF)<<16)|(((a[i+1>>2]>>8*(3-(i+1)%4))&0xFF)<<8)|((a[i+2>>2]>>8*(3-(i+2)%4))&0xFF);for(var j=0;j<4;j++){if(i*8+j*6>a.length*32){c+=jsSHA.b64pad}else{c+=b.charAt((e>>6*(3-j))&0x3F)}}}return c};var v=function(x,n){if(n<32){return(x<<n)|(x>>>(32-n))}else{return x}};var w=function(x,y,z){return x^y^z};var A=function(x,y,z){return(x&y)^(~x&z)};var B=function(x,y,z){return(x&y)^(x&z)^(y&z)};var C=function(x,y){var a=(x&0xFFFF)+(y&0xFFFF);var b=(x>>>16)+(y>>>16)+(a>>>16);return((b&0xFFFF)<<16)|(a&0xFFFF)};var D=function(a,b,c,d,e){var f=(a&0xFFFF)+(b&0xFFFF)+(c&0xFFFF)+(d&0xFFFF)+(e&0xFFFF);var g=(a>>>16)+(b>>>16)+(c>>>16)+(d>>>16)+(e>>>16)+(f>>>16);return((g&0xFFFF)<<16)|(f&0xFFFF)};var E=function(f,g){var W=[];var a,b,c,d,e;var T;var H=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0];var K=[0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x5a827999,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x6ed9eba1,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0x8f1bbcdc,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6,0xca62c1d6];f[g>>5]|=0x80<<(24-g%32);f[((g+1+64>>9)<<4)+15]=g;var h=f.length;for(var i=0;i<h;i+=16){a=H[0];b=H[1];c=H[2];d=H[3];e=H[4];for(var t=0;t<80;t++){if(t<16){W[t]=f[t+i]}else{W[t]=v(W[t-3]^W[t-8]^W[t-14]^W[t-16],1)}if(t<20){T=D(v(a,5),A(b,c,d),e,K[t],W[t])}else if(t<40){T=D(v(a,5),w(b,c,d),e,K[t],W[t])}else if(t<60){T=D(v(a,5),B(b,c,d),e,K[t],W[t])}else{T=D(v(a,5),w(b,c,d),e,K[t],W[t])}e=d;d=c;c=v(b,30);b=a;a=T}H[0]=C(a,H[0]);H[1]=C(b,H[1]);H[2]=C(c,H[2]);H[3]=C(d,H[3]);H[4]=C(e,H[4])}return H};this.getHash=function(a){var b=null;var c=r.slice();if(m===null){m=m=E(c,q)}switch(a){case"HEX":b=s;break;case"B64":b=u;break;default:return"FORMAT NOT RECOGNIZED"}return b(m)};this.getHMAC=function(a,b,c){var d=null;var e=null;var f=[];var g=[];var h=null;var j=null;switch(c){case"HEX":d=s;break;case"B64":d=u;break;default:return"FORMAT NOT RECOGNIZED"}if("HEX"===b){if(0!==(a.length%2)){return"KEY MUST BE IN BYTE INCREMENTS"}e=p(a);j=a.length*4}else if("ASCII"===b){e=o(a);j=a.length*jsSHA.charSize}else{return"UNKNOWN KEY INPUT TYPE"}if(512<j){e=E(e,j);e[15]&=0xFFFFFF00}else if(512>j){e[15]&=0xFFFFFF00}for(var i=0;i<=15;i++){f[i]=e[i]^0x36363636;g[i]=e[i]^0x5C5C5C5C}h=E(f.concat(r),512+q);h=E(g.concat(h),672);return(d(h))}};
	
	
 	var escapable = /[\\\"\x00-\x1f\x7f-\uffff]/g,
        meta = {    // table of character substitutions
            '\b': '\b',
            '\t': '\t',
            '\n': '\n',
            '\f': '\f',
            '\r': '\r',
            '"' : '"',
            '\\': '\\'
        };


	function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                 	'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) :
             string ;
    };
	
	var gen_sig = function(params) {
		
		var base_string = encode(params); 
		
		var secret = readCookie(SECRET_COOKIE_KEY);
		if (secret) {
			var hmacObj = new jsSHA(base_string, 'ASCII');
		
			var sig = hmacObj.getHMAC(secret,
							'ASCII',
							"HEX");
			params["sig"] = sig;
		}
	};
	
	var call = function(type, success, error, params, sign) {
		_request_error = error; 
		_request_success = success;
		
		if (sign) {
			if (params) {
				gen_sig(params); 
			}
		}
		
		var query_string = '';
		if (type == 'DELETE') {
			query_string = '?'; 
			counter = 0;
			for (var key in params) {
				if (counter == 0) {
					query_string += key + '=' + params[key];
				}else {
					query_string += '&' + key + '=' + params[key];
				}
				counter++;
			}
		}
		
		var options = {
			type: type,
			url: _service_url + '/' + _entity + query_string,
			success: function (data, textStatus, XMLHttpRequest) {
						load_success(data, _object);
					 },
			error: function (XMLHttpRequest, textStatus, errorThrown){
				
						if (XMLHttpRequest.status != 0) {
							load_error(textStatus, errorThrown, _object);
						}
					},
			complete: function(XMLHttpRequest, textStatus) {
				if (_complete_fn) {
					_complete_fn(_object);
				}
			},
			dataType: "json"
		}
		
		if (type != 'DELETE') {
			options["data"] = params;
		}
		
		if (_async != null) {
			options["async"] = _async;
		}
		$.ajax(options);			
	};
	
	return {
		init : function(entity, object, async){
			_entity = entity;
			if (object) {
				_object = object;
			}
			if (async != null) {
				_async = async;
			}
		},
		
		set_complete_fn : function(fn) {
			_complete_fn = fn;
		},
		
		//for testing purpose 		
		trigger_load_success : function(data) {
			load_success(data);
		}, 
		
		//for testing purpose 
		trigger_load_error : function(xhr, status, err) {
			load_error(data);
		}, 
	
		get : function(success, error, params, sign) {
			sign = sign === undefined ? false : sign;
			call('GET', success, error, params, sign);
		},
		
		post : function(success, error, params, sign) {
			sign = sign === undefined ? true : sign;			
			call('POST', success, error, params, sign);
		}, 
		
		del : function(success, error, params, sign) {
			sign = sign === undefined ? true : sign;	
			call('DELETE', success, error, params, sign);
		}
	}
};

var MNUser = function() {
	
	var _userid = null
	var _username = null; 
	var _userpic = null; 
	var _locale = null;
	var _sessionToken = null; 
	
	return {
		logout : function() {

			eraseCookie(APIKEY_COOKIE_KEY);
			eraseCookie(SECRET_COOKIE_KEY);
			eraseCookie(TOKEN_COOKIE_KEY);
			eraseCookie(NICK_NAME_COOKIE_KEY);
			eraseCookie(USER_ID_COOKIE_KEY);
			eraseCookie(PIC_COOKIE_KEY); 
			eraseCookie(LOCALE_COOKIE_KEY);
		},
		
		show_login : function(verb) {
			
			var panel = $('div#login-panel'); 
			$('span.verb', panel).text(verb); 
			$('a.btn-cancel', panel).click(function() {
				panel.hide();
				$(this).unbind('click');
			});
			var width = $(document).width();
			
			panel.css("top", ( $(window).height() - panel.height() ) / 2+$(window).scrollTop() + "px");
		    panel.css("left", ( $(window).width() - panel.width() ) / 2+$(window).scrollLeft() + "px");

			panel.css("z-index", "9999");
			panel.show();
			
		}, 
		get_sessionToken : function() {
			if (_sessionToken == null) {
				_sessionToken = readCookie(TOKEN_COOKIE_KEY);
			}
			return _sessionToken;
		},
		
		get_nickname : function() {
			if (_username == null) {
				_username = readCookie(NICK_NAME_COOKIE_KEY);
			}
			return _username;
		},
		get_userid : function() {
			if (_userid == null) {
				_userid = readCookie(USER_ID_COOKIE_KEY);
			}
			return _userid;
		},
		get_userpic : function() {
			if (_userpic == null) {
				_userpic = readCookie(PIC_COOKIE_KEY);
			}
			return _userpic;
		},		
		get_locale : function() {
			var locale =  readCookie('django_language');
			if (locale)
				return locale;
			else
				return 'en_US';
		},
		get_language : function() {
			var locale =  readCookie('django_language');
			if (locale)
				if (locale.toLowerCase() == 'zh_tw' || 
					locale.toLowerCase() == 'zh_hk' ||
					locale.toLowerCase() == 'zh_cn' ) {
					return 'zh';
				}else{
					var idx = locale.indexOf('_');
					if (idx != -1) {
						return locale.substring(0, locale.indexOf('_'));
					}else{
						return 'en';
					}
				}
			else
				return 'en';
		},
		is_logged_in : function() {
			if (readCookie(TOKEN_COOKIE_KEY))
				return true;
			else
				return false;
		},
		
		is_login_user : function(userid) {
			if (_userid == null) {
				_userid = readCookie(USER_ID_COOKIE_KEY);
			}
			return (_userid == userid);
		}
	};
}();

var MailPrompt = function() {

	var update_email_callback = function(data) {
		var container = $(MOVNOTE.common.message_id); 
		container.empty();
	}; 
	
	var update_email_error = function(error){
		ErrorHandler.show("Error in updating email address ");
	};

				
	return {
		
		grant_mail : function(success_callback) {
			FB.login(function(response) {
			  if (response.session) {
			    if (response.perms) {
			      // user is logged in and granted some permissions.
			      // perms is a comma separated list of granted permissions
					FB.api('/me', function(response) {
						if (response.email) {
							var req = MNRequest(); 
							req.init('user'); 
							req.post(update_email_callback, update_email_error, 
								{feed:'{"email":"' + response.email + '"}'});
						}
					});
					if (typeof success_callback === 'function') {
						success_callback();
					}
			    } else {
					var container = $(MOVNOTE.common.message_id); 
					container.empty();
			    }
			  } else {
			    // user is not logged in
			  }
			}, {perms:'email'});
		},
		
		show : function(msg) {

			var container = $(MOVNOTE.common.message_id); 
			container.empty();
				var msg = $(['<div id="message-div"><span><b>Would you like to receive notifications (activity of your account) <br/>from Movnote ? </b><a id="reject-mail">No, Thanks</a>',
						,'</span><a id="grant-mail" class="vthin-button discard" style="float:right">',
						'<span>Yes, Please</span></a><div style="clear:both;"></div></div>'].join('')).appendTo(container); 

			$("a#reject-mail", container).click(function() {
				var req = MNRequest(); 
				req.init('user'); 
				req.post(null, null, 
					{feed:'{"rej_mail":true}'});
				msg.remove(); 
			})
			
			$("a#grant-mail", container).click(this.grant_mail);					
		}

	};	
}();

var ErrorHandler = function() {
	return {
		show : function(msg) {
			
			var container = $(MOVNOTE.common.message_id); 
			container.empty();
			var msg = $('<div id="message-div"><span>' + msg + '</span><a class="vthin-button discard" style="float:right"><span>Discard</span></a><div style="clear:both;"></div></div>').appendTo(container); 
			
			$("a.discard", container).click(function() {
				msg.remove(); 
			})
		},
		
		warn : function(msg) {
			
		}
	};
}();


/*
    http://www.JSON2.org/JSON22.js
    2009-08-17

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON2.org/js.html

    This file creates a global JSON2 object containing two methods: stringify
    and parse.

        JSON2.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON2 text from a JavaScript value.

            When an object value is found, if the object contains a toJSON2
            method, its toJSON2 method will be called and the result will be
            stringified. A toJSON2 method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON2 method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON2 = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON2 representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON2 values.
            JSON2.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON2.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON2.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON2.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON2.parse(text, reviver)
            This method parses a JSON2 text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON2.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON2.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
*/

/*jslint evil: true */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON2, "\\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON2, toString, valueOf
*/

"use strict";

// Create a JSON2 object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON2) {
    this.JSON2 = {};
}

(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON2 !== 'function') {

        Date.prototype.toJSON2 = function (key) {

            return isFinite(this.valueOf()) ?
                   this.getFullYear()   + '-' +
                 f(this.getMonth() + 1) + '-' +
                 f(this.getDate())      + 'T' +
                 f(this.getHours())     + ':' +
                 f(this.getMinutes())   + ':' +
                 f(this.getSeconds())   + 'Z': null;
        };

        String.prototype.toJSON2 =
        Number.prototype.toJSON2 =
        Boolean.prototype.toJSON2 = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON2 method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON2 === 'function') {
            value = value.toJSON2(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON2 numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON2 values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON2 object does not yet have a stringify method, give it one.

    if (typeof JSON2.stringify !== 'function') {
        JSON2.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON2 text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON2.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON2 object does not yet have a parse method, give it one.

    if (typeof JSON2.parse !== 'function') {
        JSON2.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON2 text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON2 patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON2 backslash pairs with '@' (a non-JSON2 character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

  if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
	/*
            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
*/

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }

// If the text is not JSON2 parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON2.parse');
        };
    }
}());


