
function $pi(str) {
	return parseInt(str);
}

var mozilla = (navigator.userAgent.toLowerCase().indexOf("msie") == -1);

// String extensions ===========================================================
String.prototype.trim = function() {
	var s = this;
	while (s.substring(0,1) == ' ') {
		s = s.substring(1,s.length);
	}
	while (s.substring(s.length-1,s.length) == ' ') {
		s = s.substring(0,s.length-1);
	}
	return s;
}

String.prototype.replace = function(find, replace) {
	return this.split(find).join(replace);
}

String.prototype.format = function() {
	return this.replace('<', '&lt;').replace(' ', '&nbsp;&nbsp;').replace('\n', '<br \/>\n');
}

String.prototype.escapeForXML = function() {
	return this.replace('&', '&amp;').replace('"', '&quot;').replace('<', '&lt;').replace('>', '&gt;');
}

String.prototype.escapeForDisplay = function() {
	return this.replace('<', '&lt;');
}

String.prototype.len = function() {
	var data = this.toString();
	var len = 0;
	for(var i = 0; i < data.length; i++) {
		var c = data.charCodeAt(i);
		if (c > 0x80)
			len += 2;
		else 
			len += 1;
	}
	return len;
}
String.prototype.brief = function(length) {
	var len = 0;
	var buf = '';
	for(var i = 0; i < this.length; i++) {
		var c = this.charCodeAt(i);
		if (c > 0x80)
			len += 2;
		else 
			len += 1;
		if (len <= length)
			buf += this.charAt(i);
		else
			return buf;
	}
	return buf;
}

// ~ Class Photo ===========================================================
var Photo = Class.create();

Photo.prototype = {
	initialize: function( id, title, description, filename, dir, host, order ) {
		this.id           = id;
		this.title        = title;
		this.description  = description;
		this.filename     = filename;
		this.dir          = dir;
		this.host         = host;
		this.order        = order;
		
		this.album        = null;
	}/*,
	
	getUrl: function(v) {
		return getPhotoUrl(this.filename, this.dir, this.host, v);
	}*/
};

// ~ Class Album ============================================================
/*
var Album = Class.create();

Album.prototype = {
	initialize: function( id, title, description, date, cover, count, order) {
		this.id           = id;
		this.title        = title;
		this.description  = description;
		this.date         = date;
		this.cover        = cover;
		this.order        = order;
		
		this.count        = count;
		this.photos       = new Array();
	},
	
	getCoverUrl: function(v) {
		if (this.cover == null || !this.cover.id || this.cover.id == '') 
			return PHOTO_HOST + 'defaultSetPhoto.jpg';
		return getPhotoUrl(this.cover.filename, this.cover.dir, this.cover.host, v);
	},
	
	getPhotos: function() {
		return this.photos;
	},
	
	setPhotos: function(photos) {
		this.photos = photos;
		this._updateCount();
	},
	
	addPhoto: function(photo) {
		if (this.containsPhoto(photo))
			return false;
	
		this.photos.push(photo);
		photo.album = this;
		this._updateCount();
		
		return true;
	},
	
	removePhoto: function(photo) {
		if (!this.containsPhoto(photo))
			return false;
	
		this.photos.removeItem(photo);
		this._updateCount();
		
		return true;
	},
	
	containsPhoto: function(photo) {
		if (!photo) 
			return false;
			
		if (this.photos.contains(photo))
			return true;
			
		for (var i = 0; i < this.photos.length; i++) {
			if (this.photos[i].id == photo.id)
				return true;
		}
		
		return false;
	},
	
	_updateCount: function() {
		this.count = this.photos.length;
	}
};

*/

// ~ Utilities =================================================================

var PHOTO_HOST = 'http://file.joycity.cc/PersonalPhotobook/';

function getPhotoUrl(filename, dir, host, v) {
	var location = 'http://photo' + host + '.yupoo.com/' + dir + '/' + filename;
	switch(v) {
		case 1: return location + '_s.jpg';
		case 2: return location + '_t.jpg';
		case 3: return location + '_m.jpg';
		case 4: return location + '.jpg';
		case 5: return location + '_o.jpg';
		default: return location + '.jpg';
	}
}

//var photo_cache = {};

function parseAlbumPhotos(rsp) {
	var photos = new Array();
	var nodes = rsp.lastChild.childNodes;
	for (var i = 0; i < nodes.length; i++) {
		var node = nodes[i];
		var id = node.getAttribute('id');
		/*
		if (photo_cache[id]) {
			photos.push(photo_cache[id]);
			continue;
		}*/
		
		var title = node.getAttribute('title');
		var description = node.getAttribute('description');
		var filename = node.getAttribute('name');
		var dir = node.getAttribute('dir');
		var host = $pi(node.getAttribute('host'));
		var order = $pi(node.getAttribute('order'));
		
		var photo = new Photo(id, title, description, filename, dir, host, order);
		//photo_cache[id] = photo;
		photos.push(photo);
	}
	return photos;
}

function parseAlbum(rsp) {
	var node = rsp.lastChild;
	
	var id = node.getAttribute('id');
	var title = node.getAttribute('title');
	var description = node.getAttribute('description');
	var date = node.getAttribute('date');
	var cover = node.getAttribute('cover');
	var count = node.getAttribute('count');
	
	var album = new Album(id, title, description, date, {id: cover, dir: '', filename: '', host: 0}, count);
	
	return album;
}

function parseContext(rsp) {
	var context = { prev: null, next: null };
	var nodes = rsp.childNodes;
	for (var i = 0; i < nodes.length; i++) {
		var node = nodes[i];
		if (node.nodeName == 'prev') {
			context.prev = parseContextPhoto(node);
		} else if (node.nodeName == 'next') {
			context.next = parseContextPhoto(node);
		}
	}
	
	return context;
}

function parseContextPhoto(node) {
	var id = node.getAttribute('id');
	var title = node.getAttribute('title');
	var filename = node.getAttribute('name');
	var dir = node.getAttribute('dir');
	var host = $pi(node.getAttribute('host'));
	var photo = new Photo(id, title, '', filename, dir, host, -1);
	return photo;	
}

// ~ Class ImageStore ==========================================================
var ImageStore = Class.create();

ImageStore.prototype = {
	initialize: function() {
		this.images = {};
	},
	
	load: function(name, location) {
		if (this.images[name]) 
			return;
			
		var image = new Image();
		image.src = location;
		this.images[name] = image;
	},
	
	get: function(name) {
		return this.images[name];
	}
};

var imageStore = new ImageStore();

/*
var waiting_flash = function(msg, w, h) {
	if (arguments.length < 2) {
		w = 36;
		h = 36;
	}

	var html = '';
	html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="' + w + '" height="' + h + '">';
	html += '<param name="movie" value="/images/waiting.swf">';
	html += '<param name="quality" value="high">';
	html += '<param name="bgcolor" value="#FFFFFF">';
	html += '<embed src="/images/waiting.swf" quality="high" bgcolor="#FFFFFF" width="' + w + '" height="' + h + '" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"><\/embed>';
	html += '<\/object>';
	
	if (arguments.length > 0) {
		html += '<span style="font-weight:bold;">' + msg + '<\/span>';
	}
	
	return html;
}
*/

/* This function is used to set cookies */
function setCookie(name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}

/* This function is used to get cookies */
function getCookie(name) {
	var prefix = name + "=" 
	var start = document.cookie.indexOf(prefix) 

	if (start==-1) {
		return null;
	}
	
	var end = document.cookie.indexOf(";", start+prefix.length) 
	if (end==-1) {
		end=document.cookie.length;
	}

	var value=document.cookie.substring(start+prefix.length, end) 
	return unescape(value);
}

/* This function is used to delete cookies */
/*
function deleteCookie(name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

function cookiesDisabled() {
	var result=true;
  	// some browser versions support this - use it if possible
  	if (navigator.cookiesEnabled)
    	return false;
  
  	// else try to set and read a cookie
  	document.cookie = "testcookie=yes;";
  	var cookieSet = document.cookie;
  	if (cookieSet.indexOf("testcookie=yes") > -1) {
    	result=false;
  	}
  	document.cookie = "testcookie=;expires=;";
 	return result;
}
*/

function $pi(str) {
	return parseInt(str);
}

var mozilla = (navigator.userAgent.toLowerCase().indexOf("msie") == -1);

function escape_utf8(data) {

	if (data == '' || data == null){
		return '';
	}
	data = data.toString();
	var buffer = '';
	for(var i=0; i<data.length; i++){
		var c = data.charCodeAt(i);
		var bs = new Array();

		if (c > 0x10000){
			// 4 bytes
			bs[0] = 0xF0 | ((c & 0x1C0000) >>> 18);
			bs[1] = 0x80 | ((c & 0x3F000) >>> 12);
			bs[2] = 0x80 | ((c & 0xFC0) >>> 6);
			bs[3] = 0x80 | (c & 0x3F);

		}else if (c > 0x800){
			// 3 bytes
			bs[0] = 0xE0 | ((c & 0xF000) >>> 12);
			bs[1] = 0x80 | ((c & 0xFC0) >>> 6);
			bs[2] = 0x80 | (c & 0x3F);

		}else if (c > 0x80){
			// 2 bytes
			bs[0] = 0xC0 | ((c & 0x7C0) >>> 6);
			bs[1] = 0x80 | (c & 0x3F);

		}else{
			// 1 byte
			bs[0] = c;
		}

		for(var j=0; j<bs.length; j++){
			var b = bs[j];
			var hex = nibble_to_hex((b & 0xF0) >>> 4) + nibble_to_hex(b & 0x0F);
			buffer += '%'+hex;
		}
	}

	return buffer;
}

function nibble_to_hex(nibble){
	var chars = '0123456789ABCDEF';
	return chars.charAt(nibble);
}

//?????????????
function clearSubmit(form) {
    previous = form.action;
    if (previous.indexOf("?") != -1) {
        form.action = previous + "&clear=true";
    } else {
        form.action = previous + "?clear=true";
    }
    form.submit();
    form.action = previous;
}

function clearGoto(url) {
    if (url.indexOf("?") != -1) {
        window.location.replace(url + "&clear=true");
    } else {
        window.location.replace(url + "?clear=true");
    }
}

