/*
 * InSkin Global
 */

// InSkinObject is used to keep a global reference to all InSkin objects
// defined on a page:
if (typeof(InSkinObject) == 'undefined') {
	var InSkinObject = {};
}

if (typeof(InSkinGlobal) == 'undefined') {
	var InSkinGlobal = {};
	
	InSkinGlobal['createInSkin'] = function(InSkinParams) {
		//alert(InSkinParams['plr_InSkinID']);
		
		//eval('InSkinObject["' + InSkinParams['plr_InSkinID'] + '"] = new InSkin(InSkinParams)');
		//eval('InSkinObject["' + InSkinParams['plr_InSkinID'] + '"].initFromFlash()');
		(new InSkin(InSkinParams)).initFromFlash();
		
		return true;
	}
}




/*
 * InSkin Base
 */


//
// constructor:
//
function InSkin(params) {

	// some constants:
	//this.PLAYER_BASE_URL = 'http://alpha.onsysol.dyndns.org:8080/inskin/player';
	this.PLAYER_BASE_URL = 'http://inskin.vo.llnwd.net/o21/ISAPFiles/InSkinPlayer/player';
	this.PLAYER_URL = this.PLAYER_BASE_URL + '/base.swf?' + (new Date()).getTime();

	this.VERSION = '0.1';

	this.params = params;
	InSkinObject[this.params['plr_InSkinID']] = this;


	if (typeof($) != 'undefined') {
		var f = $;
		this.j = jQuery.noConflict();

		if (typeof($) == 'undefined') {
			$ = f;
		}
	}
	else {
		this.j = jQuery.noConflict();
	}


	//this.debug = true;
	

	this.contentStart1stTime = true;


	//
	// get information about the user (UserID, SessionID and Resolution):
	//

	// UserID is stored in a persistent cookie:
	this.pers_cookie_name = this.params['srv_SectionID'] + '_pers';
	this.pers_cookie = new CJL_CookieUtil(this.pers_cookie_name, 5 * 356 * 24 * 60, '/');
	this.UserID = this.pers_cookie.getSubValue('UserID');
	if (!this.UserID) {
		this.UserID = this.generateID();
		this.pers_cookie.setSubValue('UserID', this.UserID);
	}

	// SessionID is stored in a session cookie:
	this.sess_cookie_name = this.params['srv_SectionID'] + '_sess';
	this.sess_cookie = new CJL_CookieUtil(this.sess_cookie_name, 0, '/');
	this.SessionID = this.sess_cookie.getSubValue('SessionID');
	if (!this.SessionID) {
		this.SessionID = this.generateID();
		this.sess_cookie.setSubValue('SessionID', this.SessionID);
	}


	this.inskin_div = 'InSkinIDiv_' + this.params['plr_InSkinID'];
	if (this.params['plr_TotalW'] && this.params['plr_TotalW'] != '') {
		this.inskin_w = this.params['plr_TotalW'];
	}
	else {
		this.inskin_w = this.params['plr_InSkinW'];
	}
	if (this.params['plr_TotalH'] && this.params['plr_TotalH'] != '') {
		this.inskin_h = this.params['plr_TotalH'];
	}
	else {
		this.inskin_h = this.params['plr_InSkinH'];
	}
	this.content_div = 'InSkinCDiv_' + this.params['plr_InSkinID'];
	this.content_w = this.params['plr_ContentW'];
	this.content_h = this.params['plr_ContentH'];

	this.inskin = null;
	this.j_sasframe = null;
	this.j_content_div = null;

	this.content_div_top = null;
	this.content_div_left = null;

	this.content_resize_on_init = false;
	this.content_resize_w = 0;
	this.content_resize_h = 0;

	this.SWF_contentInit_called = false;
	
	//this.content = this.createContentObject(this.params['plr_ContentType']);
	eval('this.content = new InSkinContent_' + this.params['plr_ContentType'] + '(this);');
	this.createContentCallbacks();
}


// init (when we first embed Javascript, then Flash):
InSkin.prototype.init = function() {

	this.embedded = false;

	if (this.params['srv_UseSAS'] == 'true' || this.params['srv_UseSAS'] == 'onplay') {
		//this.sasframe = this.j('#InSkinSASFrame_' + this.params['plr_InSkinID']);
		//this.loadSASFrame();
		this.j_sasframe = this.j('#InSkinSASFrame_' + this.params['plr_InSkinID']);
		if (this.params['srv_UseSAS'] == 'true') {
			this.SASIntegration();
		}
		else {
			this.embed();
		}
	}
	else {
		this.embed();
	}

	//this.createContentCallbacks();
}

// init (when we first embed Flash, then Javascript):
InSkin.prototype.initFromFlash = function() {
	//var embed_code = this.content.embedCode();
	//content_div.html(embed_code);
	//var properties = {
	//	'top': '20px',
	//	'left': '14px'
	//};
	//content_div.css(properties).html(embed_code);
	//
	
	var j_content_div = this.j('#' + this.content_div);
	var css = {
		'left': this.params['plr_FrameSide'] + 'px',
		'top': this.params['plr_FrameTop'] + 'px'
	};
	j_content_div.css(css);
	
	this.content.embed();
	
	this.SWF_loaded();
	this.SWF_contentInit();
	//var content_div = document.getElementById('InSkinCDiv_' + this.params['plr_InSkinID']);
	//alert(content_div.html('<script>alert(1)</script>'));
}



//
// SAS Integration:
// - load the appropriate ad tags before embedding the base.
//
InSkin.prototype.SASIntegration = function() {

	var ad_tags = new Array();
	if (this.params['cnt_autostart'] && this.params['cnt_autostart'] == 'true') {
		
		if (this.params['sas_PrerollAdTag'] && this.params['sas_PrerollAdTag'] != '') {
			ad_tags[ad_tags.length] = 'sas_PrerollAdTag';
		}

		if (this.params['sas_PlayAdTag'] && this.params['sas_PlayAdTag'] != '') {
			ad_tags[ad_tags.length] = 'sas_PlayAdTag';
		}
		else if (this.params['sas_PauseAdTag'] && this.params['sas_PauseAdTag'] != '') {
			ad_tags[ad_tags.length] = 'sas_PauseAdTag';
		}
		else if (this.params['sas_code'] && this.params['sas_code'] != '') {
			ad_tags[ad_tags.length] = 'sas_code';
		}
	}
	else {
		if (this.params['sas_PauseAdTag'] && this.params['sas_PauseAdTag'] != '') {
			ad_tags[ad_tags.length] = 'sas_PauseAdTag';
		}
		else if (this.params['sas_code'] && this.params['sas_code'] != '') {
			ad_tags[ad_tags.length] = 'sas_code';
		}
	}

	this.makeSASAdCall(ad_tags, '', '');
}







// check if SAS frame has loaded:
InSkin.prototype.checkSASFrameLoaded = function(errorMethod) {
	if (!this.sasframe_loaded) {
		//alert('checkSASFrameLoaded: ' + errorMethod);
		this.contentShow();
		this.contentInit();
	}
}

// check if InSkin flash object has loaded:
InSkin.prototype.checkInSkinLoaded = function() {

	if (!this.inskin_loaded) {
		this.contentShow();
		this.contentInit();
	}
}

// handle content callbacks:
InSkin.prototype.createContentCallbacks = function() {
	var _self = this;

	this.content.onReady = function() {
		_self.onContentReady();
	}

	this.content.onStart = function() {
		_self.onContentStart();
	}
	
	this.content.onPause = function() {
		_self.onContentPause();
	}
	
	this.content.onNewItem = function() {
		_self.onContentNewItem();
	}
}

//
// make an Ad Call on a SAS:
//
InSkin.prototype.makeSASAdCall = function(adTags, successMethod, errorMethod) {

	this.sasframe_loaded = false;

	var ad_tags = adTags.join(',');
	//alert(ad_tags);

	//
	// generate the content for the SAS IFRAME:
	//
	var sasframe_src = '';
	sasframe_src += '<html><body><script type="text/javascript">';
	sasframe_src += 'var inskin_obj = window.parent.' + this.params['plr_InSkinID'] + ';';
	sasframe_src += 'var inskin_sascode = inskin_obj.getSASCode("' + ad_tags + '");';
	//sasframe_src += 'alert(inskin_sascode);';
	sasframe_src += 'document.write(inskin_sascode);';

	//sasframe_src += 'document.write("<scr" + "ipt src="' + 'http://alpha.onsysol.dyndns.org:8080/inskin/ikit/js/inskin/inskin_sas.js' + '"></scr" + "ipt>");';
	sasframe_src += 'window.onload = function() { if (typeof(isapAdvertID) != "undefined" && typeof(isapClickUrl) != "undefined") { inskin_obj.SASFrameLoaded(isapAdvertID, isapClickUrl, "' + successMethod + '"); } else if (typeof(isapAdvertIDs) != "undefined" && typeof(isapClickURLs) != "undefined") { inskin_obj.SASFrameLoaded(isapAdvertIDs, isapClickURLs, "' + successMethod + '"); } else if (typeof(InSkinAdverts) != "undefined" && typeof(InSkinURLs) != "undefined") { inskin_obj.SASFrameLoaded3(InSkinAdverts, InSkinURLs); } else { inskin_obj.SASFrameError("' + errorMethod + '"); } }';
	sasframe_src += '</script></body></html>';

	//alert(sasframe_src);

	if (this.params['sas_FrameURL'] && this.params['sas_FrameURL'] != '') {
		var url = this.params['sas_FrameURL'] + '?id=' + escape(this.params['plr_InSkinID']) + '&ad_tags=' + escape(ad_tags);
		if (this.params['sas_FrameDomain'] && this.params['sas_FrameDomain'] != '') {
			url += '&domain=' + escape(this.params['sas_FrameDomain']);
		}
		
		this.j_sasframe.attr('src', url);
		//alert(this.j_sasframe.attr('src'));
	}
	else {
		this.j_sasframe.attr('src', "javascript: '" + sasframe_src + "'");
	}

	// make sure the SAS frame takes a reasonable time to load:
	var _self = this;
	setTimeout(function() { _self.checkSASFrameLoaded(errorMethod); }, 5000);
}

InSkin.prototype.getSASCode = function(ad_tags) {
	var code = '';
	var adTags = ad_tags.split(/,/);

	for (var i = 0; i < adTags.length; i++) {
		code += this.URLDecode(this.params[adTags[i]]);
	}

	return code;
}

InSkin.prototype.getSASFrameIncludes = function() {
	var url = 'http://192.168.1.2/inskin/ikit/js/inskin/inskin_sas.js';
	return '<scr' + 'ipt type="text/javascript" src="' + url + '"></scr' + 'ipt>';
}

InSkin.prototype.SASFrameLoaded = function(advert, click, successMethod) {

	var advert_ids = '';
	var click_urls = '';

	if (typeof(advert) == 'string') {
		advert_ids = advert;
	}
	else if (typeof(advert) == 'object') {
		advert_ids = advert.join(',');
	}
	if (typeof(click) == 'string') {
		click_urls = click;
	}
	else if (typeof(click) == 'object') {
		click_urls = click.join(',inskin_sep,');
	}
	
	click_urls = escape(click_urls);
	//alert('advert_ids: ' + advert_ids + '; click_urls: ' + click_urls);
	this.sasframe_loaded = true;
	
	if (this.embedded) {
		
		var section_id = false;
		if (this.params['srv_SectionIDPlay'] && this.params['srv_SectionIDPlay'] != '') {
			section_id = this.params['srv_SectionIDPlay'];
		}
		else if (this.params['srv_SectionID'] && this.params['srv_SectionID'] != '') {
			section_id = this.params['srv_SectionID'];
		}

		if (section_id) {
			//alert('reload creative... SAS');
			var params = {
				'srv_UseSAS': 'true',
				'srv_SectionID': section_id,
				'srv_AdvertIDs': advert_ids,
				'plr_ClickUrl': click_urls
			};
			try {
				this.inskin.makeInSkinAdCall(params);
			}
			catch (e) {
			}
		}
	}
	else {
		this.embedded = true;
		this.params['srv_AdvertIDs'] = advert_ids;
		this.params['plr_ClickUrl'] = click_urls;
		this.embed();
	}
}

InSkin.prototype.updateBaseParams = function(p) {
	//for (var k in p) alert(k + ' = ' + p[k]);
	try {
		this.inskin.updateBaseParams(p);
	}
	catch (e) {
		//alert(e.description);
	}
}

InSkin.prototype.SASFrameLoaded3 = function(InSkinAdverts, InSkinURLs) {
	this.sasframe_loaded = true;

	var plr_PrerollClickURL = '';
	var plr_PrerollInteractionURL = '';
	var plr_SkinClickURL = '';
	var plr_SkinInteractionURL = '';
	for (var i = 0; i < InSkinURLs.length; i++) {
		if (InSkinURLs[i].type == 'interaction') {
			if (InSkinURLs[i].target == 'preroll') {
				plr_PrerollInteractionURL = escape(InSkinURLs[i].data);
			}
			else if (InSkinURLs[i].target == 'skin') {
				plr_SkinInteractionURL = escape(InSkinURLs[i].data);
			}
		}
		else if (InSkinURLs[i].type == 'click') {
			if (InSkinURLs[i].target == 'preroll') {
				plr_PrerollClickURL = escape(InSkinURLs[i].data);
			}
			else if (InSkinURLs[i].target == 'skin') {
				plr_SkinClickURL = escape(InSkinURLs[i].data);
			}
		}
	}

	var srv_PrerollAdvertID = '';
	var srv_SkinAdvertID = '';
	for (var i = 0; i < InSkinAdverts.length; i++) {
		switch (InSkinAdverts[i].target) {
			case 'preroll': srv_PrerollAdvertID = InSkinAdverts[i].data; break;
			case 'skin': srv_SkinAdvertID = InSkinAdverts[i].data; break;
		}
	}
	var arr = new Array();
	if (srv_PrerollAdvertID != '') arr[arr.length] = srv_PrerollAdvertID;
	if (srv_SkinAdvertID != '') arr[arr.length] = srv_SkinAdvertID;
	var srv_AdvertIDs = arr.join(',');

	var p = {
		'srv_AdvertIDs': srv_AdvertIDs,
		'plr_PrerollClickURL': plr_PrerollClickURL,
		'plr_PrerollInteractionURL': plr_PrerollInteractionURL,
		'plr_SkinClickURL': plr_SkinClickURL,
		'plr_SkinInteractionURL': plr_SkinInteractionURL
	};
	//for (var k in p) alert(k + ' = ' + p[k]);
	
	if (this.embedded) {
		var section_id = false;
		if (this.params['srv_SectionIDPlay'] && this.params['srv_SectionIDPlay'] != '') {
			section_id = this.params['srv_SectionIDPlay'];
		}
		else if (this.params['srv_SectionID'] && this.params['srv_SectionID'] != '') {
			section_id = this.params['srv_SectionID'];
		}

		if (section_id) {
			p['srv_UseSAS'] = 'true';
			p['srv_SectionID'] = section_id;
			
			try {
				this.inskin.makeInSkinAdCall(p);
			}
			catch (e) {
			}
		}
	}
	else {
		this.embedded = true;
		for (var k in p) this.params[k] = p[k];
		this.embed();
	}
}

InSkin.prototype.SASFrameLoaded2 = function(advertIDs, clickURLs) {
	var advert_id = advertIDs.join(',');
	var click_url = clickURLs.join(',');
	this.SASFrameLoaded(advert_id, click_url);
}

InSkin.prototype.SASFrameError = function() {
	//alert('error');
	this.sasframe_loaded = true;
	this.contentMakeBigger();
	this.contentShow();
	this.contentInit();
}

//
// embed the flash object:
//
InSkin.prototype.embed = function() {

	this.embedded = true;

	this.inskin_loaded = false;
	this.embedSWF();

	// make sure our flash takes a reasonable time to load:
	var _self = this;
	setTimeout(function() { _self.checkInSkinLoaded(); }, 5000);
}

// embed using SWFObject:
InSkin.prototype.embedSWF = function() {

	var flashvars = {
		'srv_UserID': this.UserID,
		'srv_SessionID': this.SessionID,
		'srv_Resolution': screen.width
	};
	var params = {
		'base': this.PLAYER_BASE_URL + '/',
		'allowscriptaccess': 'always',
		'wmode': 'transparent',
		'swliveconnect': true
	};
	var attributes = {
		'id': this.params['plr_InSkinID'],
		'name': this.params['plr_InSkinID']
	};

	for (var k in this.params) {
		if (k.match(/^(srv|plr|cnt|skn)_/)) {
			if (k == 'srv_SectionID' || k == 'srv_SectionIDPlay') continue;
			//alert(k + ' = ' + this.params[k]);
			flashvars[k] = this.params[k];
		}
	}

	if (this.params['srv_UseSAS'] == 'onplay') {
		flashvars['srv_UseSAS'] = 'false';
		this.params['srv_UseSAS'] = 'true';
	}

	if (this.params['cnt_autostart'] && this.params['cnt_autostart'] == 'true') {
		if (this.params['srv_SectionIDPlay'] && this.params['srv_SectionIDPlay'] != '') {
			flashvars['srv_SectionID'] = this.params['srv_SectionIDPlay'];
		}
		else {
			flashvars['srv_SectionID'] = this.params['srv_SectionID'];
		}
	}
	else {
		flashvars['srv_SectionID'] = this.params['srv_SectionID'];
	}

	swfobject.embedSWF(this.PLAYER_URL, this.inskin_div, this.inskin_w, this.inskin_h, '8.0.0', '', flashvars, params, attributes);
}

// test:
InSkin.prototype.test = function() {
	alert('Test called on InSkin object: ' + this.params['plr_InSkinID']);
}




//
// methods called from Flash:
//

// flash loaded:
InSkin.prototype.SWF_loaded = function() {
	//if (this.debug) alert('SWF_loaded called.');
	this.inskin_loaded = true;
	//this.inskin = this.j('#' + this.params['plr_InSkinID']);
	this.inskin = document.getElementById(this.params['plr_InSkinID']);
}

// init content:
InSkin.prototype.SWF_contentInit = function() {
	// this should only be called once:
	if (this.SWF_contentInit_called) return;
	this.SWF_contentInit_called = true;

	this.j_content_div = this.j('#' + this.content_div);
	if (this.content_div_top == null && this.content_div_left == null) {
		this.content_div_top = this.j_content_div.css('top');
		this.content_div_left = this.j_content_div.css('left');
	}

	this.contentShow();
	this.contentInit();
}

// start/show:
InSkin.prototype.SWF_contentStartShow = function(doNotShow) {
	if (doNotShow) {
		this.contentStart();
	}
	else {
		this.contentShow();
		this.contentStart();
	}
}

// pause/hide:
InSkin.prototype.SWF_contentPauseHide = function(doNotHide) {
	if (doNotHide) {
		this.contentPause();
	}
	else {
		this.contentPause();
		this.contentHide();
	}
}


//
// start/pause and show/hide content:
//

// init:
InSkin.prototype.contentInit = function() {
	this.content.init();
}

// start:
InSkin.prototype.contentStart = function() {
	this.content.start();
}

// pause:
InSkin.prototype.contentPause = function() {
	this.content.pause();
}


InSkin.prototype.contentMakeBigger = function() {


	if (this.params['plr_ContentType'] != 'WMP') return;
	if (!this.params['plr_MaximizeContent'] && this.params['plr_MaximizeContent'] != 'true' && !this.params['plr_ContentMaximize'] && this.params['plr_ContentMaximize'] != 'true') return;

	// determine the maximum w/h for the player such that it fits inside the
	// w/h of InSkin:
	var iw = parseInt(this.params['plr_InSkinW']);
	var ih = parseInt(this.params['plr_InSkinH']);
	var w = 0;
	var h = 0;

	if (!isNaN(parseInt(this.params['plr_ContentMaxW'])) && !isNaN(parseInt(this.params['plr_ContentMaxH']))) {
		w = parseInt(this.params['plr_ContentMaxW']);
		h = parseInt(this.params['plr_ContentMaxH']);
	}
	else {
	var cw = parseInt(this.params['plr_ContentW']);
	var ch = parseInt(this.params['plr_ContentH']);
	var ar = cw / ch;

	w = iw;
	h = Math.floor(w / ar);
	if (h > ih) {
		h = ih;
		w = Math.floor(h * ar);
	}
	}



	var t = Math.round((ih - h) / 2);
	var l = Math.round((iw - w) / 2);

	//alert('W: ' + w + '; H: ' + h + '; T: ' + t + '; L: ' + l);
	
	var o = this.j('#' + this.content_div);
	o.css({
		'top': t + 'px',
		'left': l + 'px',
		'width': w + 'px',
		'height': h + 'px'
	});

	this.content_resize_on_init = true;
	this.content_resize_w = w;
	this.content_resize_h = h;
}


// show:
InSkin.prototype.contentShow = function() {
	this.j('#' + this.content_div).css('visibility', 'visible');
	if (this.content_div_top != null && this.content_div_left != null) {
		this.j('#' + this.content_div).css({
			'top': this.content_div_top,
			'left': this.content_div_left
		});
	}
}

// hide:
InSkin.prototype.contentHide = function() {
	//this.j('#' + this.content_div).css('visibility', 'hidden');
	var o = this.j('#' + this.content_div);

	if (this.content_div_top == null && this.content_div_left == null) {
		this.content_div_top = o.css('top');
		this.content_div_left = o.css('left');
	}

	o.css({
		'top': '-10000px',
		'left': '-10000px',
		'visibility': 'hidden'
	});
}


InSkin.prototype.onContentStart1stTime = function() {
	if (this.params['srv_UseSAS'] && this.params['srv_UseSAS'] == 'true') {
		this.on1stplaywithSAS();
	}
	else {
		if (this.params['srv_SectionIDPlay'] && this.params['srv_SectionIDPlay'] != '') {
			var params = {
				'srv_SectionID': this.params['srv_SectionIDPlay']
			};
			try {
				this.inskin.makeInSkinAdCall(params);
			}
			catch (e) {//alert(e);
			}
		}
	}
}

InSkin.prototype.on1stplaywithSAS = function() {

	var ad_tags = new Array();
	if (this.params['sas_PrerollAdTag'] && this.params['sas_PrerollAdTag'] != '') {
		ad_tags[ad_tags.length] = 'sas_PrerollAdTag';
	}

	if (this.params['sas_PlayAdTag'] && this.params['sas_PlayAdTag'] != '') {
		ad_tags[ad_tags.length] = 'sas_PlayAdTag';
	}

	if (ad_tags.length > 0) {
		this.makeSASAdCall(ad_tags, '', '');
	}
}



//
// content callbacks:
//

// content is ready:
InSkin.prototype.onContentReady = function() {
	/*
	if (this.content_resize_on_init) {
		this.content_resize_on_init = false;
		if (this.content.resize) this.content.resize(this.content_resize_w, this.content_resize_h);
	}
	*/

	if (this.params['cnt_autostart'] == 'true') {
		this.contentStart1stTime = false;
		this.contentStart();
	}
}

InSkin.prototype.onContentStart = function() {
	if (this.contentStart1stTime) {
		this.onContentStart1stTime();
	}
	this.contentStart1stTime = false;

	try {
		this.inskin.JS_contentStart();
	}
	catch (e) {
		//alert(e);
	}
}

InSkin.prototype.onContentPause = function() {
	try {
		this.inskin.JS_contentPause();
	}
	catch (e) {
		//alert(e);
	}
}

InSkin.prototype.onContentNewItem = function() {


	if (this.params['srv_UseSAS'] && this.params['srv_UseSAS'] == 'true') {
	
		var ad_tags = new Array();
		if (this.params['sas_PlayAdTag'] && this.params['sas_PlayAdTag'] != '') {
			ad_tags[ad_tags.length] = 'sas_PlayAdTag';
		}
		else if (this.params['sas_PauseAdTag'] && this.params['sas_PauseAdTag'] != '') {
			ad_tags[ad_tags.length] = 'sas_PauseAdTag';
		}
		else if (this.params['sas_code'] && this.params['sas_code'] != '') {
			ad_tags[ad_tags.length] = 'sas_code';
		}
		if (ad_tags.length > 0) {
			this.makeSASAdCall(ad_tags, '', '');
		}
	}
	else {

	var section_id = false;
	if (this.params['srv_SectionIDPlay'] && this.params['srv_SectionIDPlay'] != '') {
		section_id = this.params['srv_SectionIDPlay'];
	}
	else if (this.params['srv_SectionID'] && this.params['srv_SectionID'] != '') {
		section_id = this.params['srv_SectionID'];
	}

	if (section_id) {
		//alert('new ad...' + section_id);
		var params = {
			'srv_SectionID': section_id
		};
		try {
			this.inskin.makeInSkinAdCall(params);
		}
		catch (e) {
		}
	}
	}
}










//
// helper functions:
//

// generate a unique ID:
InSkin.prototype.generateID = function() {
	return parseInt(Math.random() * 1000000);
}

InSkin.prototype.str2hex = function(str) {
	var hex = '';
	var l = str.length;
	for (var i = 0; i < l; i++) {
		var h = str.charCodeAt(i).toString(16);
		if (h.length < 2) h = '0' + h;
		hex += h;
	}
	return hex;
}

InSkin.prototype.hex2str = function(hex) {
	var str = '';
	var l = hex.length;
	for (var i = 0; i < l; i += 2) {
		str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
	}
	return str;
}


// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresearch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// And thanks to everyone else who has provided comments and suggestions.
// ====================================================================

InSkin.prototype.URLEncode = function(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
				/*
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
						  */
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for
	return encoded;
}

InSkin.prototype.URLDecode = function(encoded)
{
   if (!encoded) return '';
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				//alert( 'Bad escape combination near ...' + encoded.substr(i) );
				//plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
}
