/*
 *	Name: 			buyandread.js
 *	Description:	Provides an API to services at www.buyandread.com
 *	Author:			Bjørn Håkon Noss
 *	Version:		1.5, 06.03.2008
 */


var bar;

function BuyAndRead(params) {
	this.noConflict = false;
	this.test = false;
	this.lang = "no";
	this.actions = [];
	this.scripts = [];

	this.id = {};	
	this.paramsTmp = {};
	
	//Test
	this.spTest = "spTest";
	this.sbTest = "sbTest";
	this.tnTest = "tnTest";
	this.buyTest = "buyTest";
	
	this.setDefaultParams();

	jQuery.extend(this, params);

	this.baseUrl = location.protocol + "//" + (this.test ? "test" : "www") + ".buyandread.com";
	this.secureUrl = "https://" + (this.test ? "test" : "www") + ".buyandread.com";
	this.jsonUrl = this.baseUrl + "/servlet/json?lang="+this.lang+"&action=";
	this.secureJsonUrl = this.secureUrl + "/servlet/json?lang="+this.lang+"&action=";
	this.staticUrl = location.protocol + "//" + (this.test ? "test.buyandread.com/static" : "static.buyandread.com");
	
	if (this.noConflict) jQuery.noConflict();
	
	// lang
	this.scripts.push("bar_" + this.lang);
	this.scripts.push("numberFormat");
	
	jQuery("head").append('<link id="barCss" rel="stylesheet" href="'+this.staticUrl+'/stylesheet/bar/buyandread.css" type="text/css"/>');
	
}

//window.BuyAndRead = BuyAndRead;

BuyAndRead.text = {};

BuyAndRead.ID_SEARCH_PAGE	= "barSearchPage";
BuyAndRead.ID_SEARCH_BOX	= "barSearchBox";
BuyAndRead.ID_THUMBNAIL		= "barThumbnail";
BuyAndRead.ID_BUY			= "barBuy";
BuyAndRead.ID_LOGIN			= "barLogin";

BuyAndRead.allowedActions = [ BuyAndRead.ID_SEARCH_PAGE, BuyAndRead.ID_SEARCH_BOX, BuyAndRead.ID_THUMBNAIL, BuyAndRead.ID_BUY, BuyAndRead.ID_LOGIN ];



BuyAndRead.prototype.setDefaultParams = function() {
	this.tnUseEpaperLink = false;
}

BuyAndRead.prototype.barThumbnailSetDefaultParams = function() {
	
}

BuyAndRead.prototype.initScripts = function() {
	
	if (!this.scripts.length) return;
	
	var script = this.scripts.shift();
	var url;
	switch(script) {
		case "buyDates":	url = this.baseUrl + "/servlet/json?action=getBuyDates&pub=" + this.pub;	break;
		default:			url = this.staticUrl + "/js/bar/" + script + ".js";										break;
	}
	
	this.getScript(url);
	
}

BuyAndRead.prototype.getScript = function(url) {
	jQuery.getScript(url, function() {
		bar.scriptComplete();
	});
}
	
BuyAndRead.prototype.scriptComplete = function() {
	if (this.scripts.length) bar.initScripts();
	else this.execActions();	
}

BuyAndRead.prototype.setNumberFormat = function() {
	var nf = new NumberFormat(0);
	switch (this.lang) {
		case "no":
			nf.setSeparators(true, ' ', ',');
			
			break;
	}
	this.nf = nf;
}
	
BuyAndRead.prototype.execActions = function() {
	//alert(this.actions.length);
	
	this.setNumberFormat();
	
	for (var i = 0; i < this.actions.length; i++) {
		
		var a = this.actions[i];

		if (jQuery.inArray(a, BuyAndRead.allowedActions) == -1) continue;
		
		eval("this." + a + "SetDefaultParams();");
		if (eval("this.paramsTmp." + a)) jQuery.extend(this, eval("this.paramsTmp." + a));
		
		jQuery("#loading_" + a).hide();
		
		eval("this." + a + "Exec();");
	}
}

BuyAndRead.prototype.addAction = function(action, params) {


	if (params) eval("this.paramsTmp." + action + " = params;");
	
	var html = '<div id="' + action + '" class="buyandread"></div>';
	html += '<div id="loading_' + action + '" class="loading">';
	html += '<img src="'+this.baseUrl+'/tools/loadingAnimation.gif" alt="...loading, please wait..."/>';
	html += '</div>';
	
	document.write(html);
	if (action == BuyAndRead.ID_THUMBNAIL) {
		if (params) jQuery.extend(this, params);
		
		jQuery("#loading_" + action).hide();
		eval("this." + action + "Exec();");
	}
	else this.actions.push(action);

}

BuyAndRead.prototype.searchPage = function(params) {
	this.isSp = true;
	
	jQuery("head").append('<link rel="stylesheet" href="'+this.staticUrl+'/js/bar/simplemodal/sm.css" type="text/css"/>');
	if (jQuery.browser.msie && jQuery.browser.version < 7.0) {
		//alert("jQuery.browser.msie && jQuery.browser.version < 7.0, version: " + jQuery.browser.version);
		jQuery("head").append('<link rel="stylesheet" href="'+this.staticUrl+'/js/bar/simplemodal/sm-ie.css" type="text/css"/>');
	}
	this.scripts.push("simplemodal/jquery.simplemodal");
	jQuery("head").append('<link rel="stylesheet" href="'+this.staticUrl+'/js/bar/facebox/facebox.css" type="text/css"/>');
	this.scripts.push("facebox/facebox");
	this.scripts.push("bar_sp");
	this.addAction(BuyAndRead.ID_SEARCH_PAGE, params);
}
BuyAndRead.prototype.searchBox = function(params) {
	this.isSb = true;
	this.scripts.push("bar_sb");
	this.addAction(BuyAndRead.ID_SEARCH_BOX, params);
}
BuyAndRead.prototype.thumbnail = function(params) {
	this.isTn = true;
	this.addAction(BuyAndRead.ID_THUMBNAIL, params);
	if (params.tnWidth) jQuery("#loading_" + BuyAndRead.ID_THUMBNAIL + " > img").css({ width: params.tnWidth + "px" });
}
BuyAndRead.prototype.buy = function(params) {
	if (!this.test) return;
	this.isBuy = true;
	
	
	jQuery("head").append('<link id="barBuyCalCss" rel="stylesheet" href="'+this.staticUrl+'/js/bar/calendar/skins/aqua/theme.css" type="text/css"/>');
	this.scripts.push("bar_buy");
	this.scripts.push("calendar/calendar_stripped");
	this.scripts.push("calendar/calendar-setup_stripped");
	this.scripts.push("calendar/lang/calendar-" + this.lang);
	
	this.addAction(BuyAndRead.ID_BUY, params);
}
BuyAndRead.prototype.login = function(params) {
	if (!this.test) return;
	this.isLogin = true;
	this.scripts.push("bar_login");
	this.addAction(BuyAndRead.ID_LOGIN, params);
}


//--------------------------
// thumbnail
//--------------------------
BuyAndRead.prototype.barThumbnailExec = function() {
	this.tnWrite();
}
BuyAndRead.prototype.tnWrite = function() {
	var div = jQuery("#" + BuyAndRead.ID_THUMBNAIL);
	
	var html = "";
	
	if (this.pub) {
		var id = this.pub;
		var tnUrl = this.staticUrl + "/thumbnail/" + id + "/" + id + (this.tnLarge ? "-large" : "") + ".jpg";
		var url;
		if (this.tnUseEpaperLink) url = this.baseUrl + "/custom/bar.htm?pub=" + id;
		else if (this.tnUrl) url = this.tnUrl;
		
		if (!url) url = this.baseUrl + "/buy.htm?pub=" + id;
		
		
		var style = 'border: none; ' + (this.tnWidth ? "width: " + this.tnWidth + "px; " : "") + (this.tnHeight ? "height: " + this.tnHeight + "px; " : "")
		html += '<a href="'+url+'" target="_blank"><img src="'+tnUrl+'" alt="'+id+'" style="'+style+'" /></a>';
	}
	
	div.html(html);
}

BuyAndRead.prototype.toString = function(object) {
	var str = "";
	var o;
	
	if (object) o = object;
	else o = this;
	
	for (n in o) {
		var obj = o[n];
		if (typeof obj == "object") str += n + ": [obj]" + this.toString(obj) + "[/Obj], ";
		else if (typeof obj == "function") continue;
		else str += n + ": " + obj + ", ";
	}
	
	if(str.length > 2) str = str.substring(0, str.length-2);
	
	return str;
}

BuyAndRead.prototype.m = function(key, params) {
	return m(key, params);
}


//--------------------------
// jQuery
//--------------------------
jQuery(function() {
	if (bar) {
		bar.initScripts();
	}
	
	
});

//--------------------------
// Utils
//--------------------------


function getDateFromPfDate(pfDate) {
	pfDate = pfDate + "";
	var date = new Date();
	date.setFullYear(pfDate.substring(0, 4));
	date.setMonth(pfDate.substring(4, 6) - 1);
	date.setDate(pfDate.substring(6, 8));
	return date;
}
function getPfDateFromDate(date) {
	var y = date.getFullYear();
	var m = date.getMonth() + 1;	// integer, 0..11
	var d = date.getDate();		// integer, 1..31
			
	if (m < 10) m = "0" + m;
	if (d < 10) d = "0" + d;
			
	return "" + y + m + d;
}
	
function getCharacterCode(e) {
	var cc;
	if(e && e.which){
		e = e;
		cc = e.which;
	} else {
		e = event;
		cc = e.keyCode;
	}
	return cc;
}

function checkEnter(e) {
	var cc = getCharacterCode(e);
	if(cc == 13) {
 		getResults();
 		return false;
	}
	return true
}

function m(key, params) {
	var text = BuyAndRead.text[key];
	if (!text) {
		alert("text == null: " + text + ", key: " + key);
		return key;
	}
	if (params) {
		for (var i = 0; i < params.length; i++) {
			var p = params[i];
			text = text.replace("{"+i+"}", p);
		}
	}
	
	return text;
}

function nf(val) {
	bar.nf.setNumber(val);
	return bar.nf.toFormatted();
}



// GetUrlParameter
function gup(name) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if(results == null) return "";
	else return results[1];
}

//--------------------------
// ScrollToControl
//--------------------------
function elementPosition(obj) {
	var curleft = 0, curtop = 0;

	if (obj.offsetParent) {
    	curleft = obj.offsetLeft;
        curtop = obj.offsetTop;

        while (obj = obj.offsetParent) {
        	curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        }
    }
    return { x: curleft, y: curtop };
}

function ScrollToControl(id) {
	var elem = document.getElementById(id);
    var scrollPos = elementPosition(elem).y;
    scrollPos = scrollPos - document.documentElement.scrollTop;
    var remainder = scrollPos % 50;
    var repeatTimes = (scrollPos - remainder) / 50;
    ScrollSmoothly(scrollPos,repeatTimes);
    window.scrollBy(0,remainder);
}

var scrollRepeatCount = 0;
var scrollCTimeout;

function ScrollSmoothly(scrollPos,repeatTimes) {
	if(scrollRepeatCount < repeatTimes) {
    	window.scrollBy(0,50);
    } else {
        scrollRepeatCount = 0;
        clearTimeout(scrollCTimeout);
     	return;
    }
    scrollRepeatCount++;

    scrollCTimeout = setTimeout("ScrollSmoothly('" + scrollPos + "','"+ repeatTimes +"')",10);
}

//--------------------------
// 
//--------------------------
	

