//V3.01.A - http://www.openjs.com/scripts/jx/
jx = {
	//Create a xmlHttpRequest object - this is the constructor. 
	getHTTPObject : function() {
		var http = false;
		//Use IE's ActiveX items to load the file.
		if(typeof ActiveXObject != 'undefined') {
			try {http = new ActiveXObject("Msxml2.XMLHTTP");}
			catch (e) {
				try {http = new ActiveXObject("Microsoft.XMLHTTP");}
				catch (E) {http = false;}
			}
		//If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document.
		} else if (window.XMLHttpRequest) {
			try {http = new XMLHttpRequest();}
			catch (e) {http = false;}
		}
		return http;
	},
	// This function is called from the user's script. 
	//Arguments - 
	//	url	- The url of the serverside script that is to be called. Append all the arguments to 
	//			this url - eg. 'get_data.php?id=5&car=benz'
	//	callback - Function that must be called once the data is ready.
	//	format - The return type for this function. Could be 'xml','json' or 'text'. If it is json, 
	//			the string will be 'eval'ed before returning it. Default:'text'
	load : function (url,callback,format) {
		var http = this.init(); //The XMLHttpRequest object is recreated at every call - to defeat Cache problem in IE
		if(!http||!url) return;
		if (http.overrideMimeType) http.overrideMimeType('text/xml');

		if(!format) var format = "text";//Default return type is 'text'
		format = format.toLowerCase();

		http.open("GET", url, true);
		http.onreadystatechange = function () {//Call a function when the state changes.
			if (http.readyState == 4) {//Ready State will be 4 when the document is loaded.
				var result = "";
				if(http.responseText) result = http.responseText;
				
				//If the return is in JSON format, eval the result before returning it.
				if(result && format.charAt(0) == "j") {
					//\n's in JSON string, when evaluated will create errors in IE
					result = result.replace(/[\n\r]/g,"");
					result = eval('('+result+')'); 
				}

				//Give the data to the callback function.
				if(http.status == 0) { 
					callback();
				} else if(callback) { 
					callback(result);
				}
			}
		}
		http.send(null);
	},
	init : function() {return this.getHTTPObject();}
}
var browser = function() { var ua = navigator.userAgent;return {ie: ua.match(/MSIE\s([^;]*)/)};}();	

var BDBJS = {
	Widget: function(params,target) {
			this.init(params,target);
			return this; 
		},
		
		bind: function(that, func) {
			return function() {
				return func.apply(that, arguments);
			}
		}
}

BDBJS.Widget.prototype.params = null;
BDBJS.Widget.prototype.version = "0.9";
BDBJS.Widget.prototype.varname = null;
BDBJS.Widget.prototype.container = null;
BDBJS.Widget.prototype.containername = null;
BDBJS.Widget.prototype.target= null;
BDBJS.Widget.prototype.api_key = "344ea9689436fa662e732222949e1e9f81dcab1c";
BDBJS.Widget.prototype.api_url = "https://api.myphotodiary.com";

BDBJS.Widget.prototype.init = function(params,target) {
	this.params = params;
	this.varname = this.params.objName;
	this.containername = "bdbwidget_"+ this.params.type;
	var code="<div id='"+this.containername+"'></div>";
	if(target) {
		this.target = target;		
	} else {
		this.target = document;		
	}
   	this.target.write("<span style='display: none'>dummy</span>");
	this.target.write(code);
	this.container = this.target.getElementById(this.containername);
}
BDBJS.Widget.prototype.getData = function (url,cb) {
	this.readAPI("/users/"+this.params.userid+"/images.json?anonymous=1&plaintext=true&limit="+this.params.number+"&indent=false&allowCache=true", BDBJS.bind(this, this.JSONCallback),this.varname+".JSONCallback")
	return this;
}
BDBJS.Widget.prototype.debug = function (data) {
	if(typeof(console) != "undefined") {
		//console.log(data);
	} else {
		//alert(data.toString());
	}
}

BDBJS.Widget.prototype.showLocalDate = function (timestamp) {
  var mmToMonth = new Array("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec");
  var dt = new Date(timestamp * 1000);
  var mm = mmToMonth[dt.getMonth()];
  return dt.getDate()+ " "+ mm + " " + dt.getFullYear();
}

BDBJS.Widget.prototype.readAPI = function (uri,cb,cbstring) {
	var url = this.api_url;
	if(uri.indexOf("?") == -1) {
		url = url + uri + "?";
	} else {
		url = url + uri + "&";
	}
	url = url + "api_key=" + this.api_key;
	if(typeof ActiveXObject != 'undefined') {
		this.IEJSON(url,cbstring);
	} else {
		jx.load(url,cb,"json","GET");
	}
	return true;
}

BDBJS.Widget.prototype.IEJSON = function (url,cb) {
	var head = this.target.getElementsByTagName("head").item(0);
	var request = url+"&callback="+cb;
	var script = this.target.createElement("script");
	script.setAttribute("type", "text/javascript");
	script.setAttribute("src", request);
	head.appendChild(script);
	return true;
}
BDBJS.Widget.prototype.JSONCallback = function (data) {
	if(data && data.images) {
		this.prepareHTML(data.images);
	} else {
		this.prepareError(data);		
	}
}

BDBJS.Widget.prototype.prepareError = function (data) {
	var errorText = "An error ocurred";
	if(data && data.error)	 errorText = data.error;
	this.container.innerHTML = errorText;
}

BDBJS.Widget.prototype.bindload = function (data) {
	if(this.target.getElementById("trigger")!=null){
		if(!this.target.getElementById("trigger").offsetHeight) {
			setTimeout(BDBJS.bind(this,this.bindload),100);
		} else {
			this.target.getElementById("trigger").style.display ="none";
			this.bind().polish();
		}
	}
}
BDBJS.Widget.prototype.bind = function (data) {
	// bind click
	if(!this.params.nobindclicks) {
		var wrapper =  this.container.getElementsByTagName("div").item(0).getElementsByTagName("div").item(0);
		var divs = wrapper.childNodes;
		for( index in divs) {
			if(divs.item(index).className == "bdb_imgItem") {
				var item =  divs.item(index);
				item.getElementsByTagName("a").item(0).onclick = function() { return false };
					item.onclick = function() {document.location.href = this.getElementsByTagName("a").item(0).href};
			}
		}	
	}

	return this;
}

BDBJS.Widget.prototype.polish = function (data) {
	if(this.params.height) {
		var titleHeight = (this.params.features.header!="") ? this.container.getElementsByTagName("h3").item(0).offsetHeight : 0;
		var wrapper = this.container.getElementsByTagName("div").item(0).getElementsByTagName("div").item(0);
		var footer =  this.container.getElementsByTagName("div").item(0).getElementsByTagName("div").item(this.params.number*2+1);
		var border = 2 * this.params.theme.borderWidth;
		if(browser.ie) {
			var extraMinusHeight=0;
		} else {
			var extraMinusHeight=6;
		}
		var wrapperHeight = this.params.height-titleHeight-footer.offsetHeight-border-extraMinusHeight;
		if(wrapperHeight>0){
			wrapper.style.height = wrapperHeight + "px";
			//this.debug("höjden var: " +titleHeight + " så jag sätter den till "+this.params.height + "-" + titleHeight + "-" + footer.offsetHeight + "-"+extraMinusHeight+"= " + (this.params.height-titleHeight-extraMinusHeight))
		}
	}
	return this;

}

BDBJS.Widget.prototype.prepareHTML = function (data) {
	//var dobg=false;

	widgetClass = "bdb_widget";
	if(this.params.features.imageSize == 'full') {
		widgetClass += " bdb_full";
	} else {
		widgetClass += " bdb_small";
			/*if(!this.params.features.caption) {
				dobg = true;
			}*/
	}
	if(this.params.features.caption!="none") {
		widgetClass += " bdb_captions";
	} else {
		widgetClass += " bdb_nocaptions";
	}
	if(this.params.features.timestamp) {
		widgetClass += " bdb_dates";
	}


	var code='<div class="'+widgetClass+'">\n';
	if(this.params.features.header!=""){
		code += '<h3 class="bdb_title">'+this.params.features.header+'</h3>\n';
	}
	code += '<div class="bdb_imgWrap">\n';
	for(index in data) {
		if(typeof(data[index]) == "object") {
			image = data[index];
			var link = image.link;
	
			switch(this.params.languageid) {
				case 1:
					var domain = "bilddagboken.se";
					var link = link.replace(/myphotodiary.com/,"bilddagboken.se");
					break;
				case 5:
				default:
					var domain = "myphotodiary.com";
					break;
				
			}
			var userlink = "http://"+this.params.username+"."+domain+"/";
	
			link += "&i_f=wi";
			userlink += "?i_f=wi";
	
			if(this.params.nobindclicks) {
				link = "#";
				userlink = "#";
			}
	
			
	
			var text = image.text;
			var date = image.date;
			if(this.params.features.caption == "limit") {
				if(text.length > this.params.features.captionLimit) {
					text = text.substr(0,this.params.features.captionLimit)+"...";
				}
			}
			code += '\
			<div class="bdb_imgItem">\
				<div class="bdb_frame">';
	
			if(this.params.features.imageSize == 'full') {
				var imagesrc = image.image;
				code += '\
					<a href="'+link+'" target="_top" class="bdb_Imglink">\
					<img src="'+imagesrc+'" alt=""></a>';
			} else {
				var imagesrc = image.thumbnail;
				code += '\
					<a href="'+link+'" target="_top" class="bdb_Imglink" style="background-image:url('+imagesrc+');"></a>';
			}
			/*if(dobg) {
				} else {
			}*/
			code += '\
				</div>';
	
			if(this.params.features.caption != "none") code += '<p class="bdb_caption">'+text;
			if(this.params.features.timestamp && (this.params.features.caption != "none")) code +='<span class="bdb_ts">'+this.showLocalDate(date)+'</span>';
			if(this.params.features.caption != "none") code += '</p>';
			code += '\
		    </div>';
			
		}
	}
	code +=' \
	</div> \
    <div class="bdb_footer">\
        <a href="'+userlink+'" id="bdb_logolink" target="_top"><img width="117" height="20" src="'+this.params.features.logo+'" alt="'+domain+'"></a>\
    </div><div id="trigger"></div>\
</div>';
	var head = this.target.getElementsByTagName("head").item(0);
	var cssElement = this.target.createElement('link');
	cssElement.setAttribute('type','text/css');
	cssElement.setAttribute('href','http://images2.bilddagboken.se/static/widget-'+this.version+'.css');
	cssElement.setAttribute('rel','stylesheet');
	cssElement.setAttribute('id','stylesheetElement');
	head.appendChild(cssElement);

	var styleElement = this.target.createElement('style');
	styleElement.setAttribute('type','text/css');
	styleElement.setAttribute('id','stylesElement');
	var pMwidth = this.params.width-170;

	var borderwidth=0
	if(!browser.ie && this.params.theme.borderWidth) {
		var borderwidth=2 * this.params.theme.borderWidth;
	}
	
	var divWidth = "auto";
	if(this.params.width) divWidth =  this.params.width - borderwidth +"px";
	var divHeight = "auto";
	if(this.params.height) divHeight = this.params.height - borderwidth+"px";

	var rules = "";
	rules += '.bdb_widget{width:'+divWidth+';height:'+divHeight+';';
	if(this.params.features.font){
		rules += 'font-family:'+this.params.features.font+';';
	}
	if(this.params.features.fontsize){
		rules += 'font-size:'+this.params.features.fontsize+'px;';
	}
	rules += '}\n';
	if(this.params.features.scrollbar){
		rules += '.bdb_widget .bdb_imgWrap{overflow:auto;}\n';
	} else {
		pMwidth = pMwidth+17;
	}
	rules += '.bdb_widget.bdb_small.bdb_captions p.bdb_caption{width:'+pMwidth+'px;}\n';
	rules += this.parseTheme();
	if(browser.ie) {
		if(this.params.features.imageSize == 'full'){
			rules += '.bdb_widget.bdb_full .bdb_imgWrap .bdb_imgItem img{width:100%;}\n';
			
		}
		styleElement.styleSheet.cssText = rules;
	} else {
		var frag = this.target.createDocumentFragment();
		frag.appendChild(this.target.createTextNode(rules));
		styleElement.appendChild(frag);
	}
	head.appendChild(styleElement);

	var loc = window.location + "";
	if(loc.match(/devote\.se/gi)) {
		this.container = document.getElementById(this.container.id);
	}

	this.container.innerHTML = code;
	this.bindload();
	return true;
}
BDBJS.Widget.prototype.parseTheme = function (data) {
	var css="";
	css += ".bdb_widget{background-color:"+this.params.theme.color_background+";";
	css += "border-color:"+this.params.theme.color_border+";";
	css += "border-width:"+this.params.theme.borderWidth+";}\n";
	css += ".bdb_widget p.bdb_caption{color:"+this.params.theme.color_text+";}\n";
	css += ".bdb_widget h3.bdb_title{color:"+this.params.theme.color_header+";}\n";
	css += ".bdb_widget h3.bdb_title,.bdb_widget .bdb_footer{background-color:"+this.params.theme.color_top+";}\n";
	return css;
}