/**
 * HyvesConnect v1.0
 * @author Youri op 't Roodt
 */
var Hyves = Hyves || {};

Hyves.connect = function(){
   	/** check for environment **/
   	var aS = document.getElementsByTagName("script");
   	var env = false;
    for(var i = 0; i < aS.length; i++){
    	var s = aS[i];
    	// look for the original includes and base url
    	if(s.src && s.src.match(/precompiled\/hyvesconnect\.js(\?.*)?$/)){
	    	env = s.src.match(/\?.*env=([a-z,]*)/);
			var base_url = s.src.match(/(http:\/\/[a-z0-9\_\-\.]*)\//)[1];
    	}
    }

    var environment = (env ? env[1] : 'live');
    var isLive = environment == 'development' ? false : true;
	/** end of environment check **/
    var loggin_is_enabled = false;

	var HYVES_TYPE_BLOGITEM = 9;
	var HYVES_TYPE_TIP = 11;
	var HYVES_TYPE_WIDGET = 27;
	var HYVES_TYPE_HUB = 29;
	var HYVES_TYPE_HUBINTEREST = 43;

	var params = [];
	var aOption = [];

	var log = {
		debug: function(obj){
			if(loggin_is_enabled){
				console.log(obj);
			}
		}
	}

	var builder = {
		/**
		 * Build form and convert property bag to form input elements
		 */
		buildForm: function (id){
			var div = document.getElementById(config.getDivId());

			div.innerHTML += '<div style="display: none;"><form method="'+config.getFormMethod()+'" id="'+config.getFormId()+
							'" action="'+config.getPostUrl()+
							'" target="targetWindow"></form></div>';

			var formX = document.getElementById(config.getFormId());
			log.debug(formX);
			var par = params[id];
			for(property in par ){
				if(par.hasOwnProperty(property)){
					var node = document.createElement('input');
					node.type = 'hidden';
					node.name = property;
					node.value = par[property];
					log.debug(node);
					formX.appendChild(node);
				}
			}
		},

		getIFrameHeight: function(type){
			var height = 660;
			switch(type){
				case HYVES_TYPE_BLOGITEM:
					height = 560;
					break;

				case HYVES_TYPE_TIP:

					break;

				case HYVES_TYPE_WIDGET:

					break;

				case HYVES_TYPE_HUB:
					height = 400;
					break;

				case HYVES_TYPE_HUBINTEREST:
					height = 300;
					break;

				default:
					height = 660;
			}

			return height;
		},

		insertIFrame: function(id){
			var parentElement = document.createElement('div');
			parentElement.innerHTML += this.buildCloseButton();
			parentElement.innerHTML += '<iframe id="hyvesconnect_iframe" name="targetWindow" frameborder="0" src=""></iframe>';;

			document.body.appendChild(parentElement);

			var iFrame = document.getElementById('hyvesconnect_iframe');

			iFrame.style.backgroundColor = '#FFFFFF';
			iFrame.style.width = '515px';
			iFrame.style.height = builder.getIFrameHeight(params[id]['type'])+'px';
			var iFrameDimensions = helper.getElementDimensions(iFrame);

			this.decorateDiv(parentElement);
			var dimensions = helper.getDocumentDimensions();
			var scrollOffset = helper.getScrollOffset();
			parentElement.style.left = Math.floor((dimensions.width/2) - (iFrameDimensions.width/2) + scrollOffset.left)+'px';
			var top = (Math.floor((dimensions.height/2) - (iFrameDimensions.height/2) + scrollOffset.top));
			parentElement.style.top = top > 0 ? top+'px' : 0+'px';
		},

		insertForm: function(id){
			var div = document.getElementById(config.getDivId());
			document.body.appendChild(div);
			this.buildForm(id);
			document.getElementById(config.getFormId()).submit();
		},

		buildButton: function(id){
			var size = [16,24].join('|').indexOf(aOption[id].iconsize) < 0 ? 24 : aOption[id].iconsize;

			return '<a href="javascript:;" onclick="Hyves.connect.submit('+id+
					');"><img style="border:0px;" src="'+config.getCacheUrl()+
					'/images/hyvesconnect/favicon_'+size+'_round.png" title="Voeg toe aan Hyves"></a>';
		},

		decorateDiv: function(element){
			element.style.padding = '15px';
			element.style.backgroundColor = 'rgb(207, 223, 239)';
			element.id = config.getDivId();
			element.style.position = 'absolute';
		},

		buildCloseButton: function(){
			return '<div onclick="Hyves.connect.close();" id="hyvesconnect_close" '+
					'style="background: transparent url('+config.getCacheUrl()+
					'/images/popupbutton-sprite.gif) no-repeat scroll 0% 0%;'+
					' overflow: hidden; position: absolute; width: 15px; height: 15px;'+
					' cursor: pointer; margin-left: 2px; left: 528px; top: 0px;">';
		}
	}

	var helper = {
		getScrollOffset: function(){
			var element = document.body;
		    var valueT = 0, valueL = 0;
		    do {
		      valueT += element.scrollTop  || 0;
		      valueL += element.scrollLeft || 0;
		      element = element.parentNode;
		    } while (element);
		    return {left: valueL, top: valueT};
		},

		getDocumentDimensions: function(){
			var viewportwidth;
			var viewportheight;
			// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
			if (typeof window.innerWidth != 'undefined'){
				viewportwidth = window.innerWidth,
				viewportheight = window.innerHeight
			}
			// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
			else if (typeof document.documentElement != 'undefined'
				&& typeof document.documentElement.clientWidth !=
				'undefined' && document.documentElement.clientWidth != 0)
			{
				viewportwidth = document.documentElement.clientWidth,
				viewportheight = document.documentElement.clientHeight
			}
			else{// older versions of IE
				viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
				viewportheight = document.getElementsByTagName('body')[0].clientHeight
			}
			return {width: viewportwidth, height: viewportheight};
		},

		getElementDimensions: function(element){
			return {width: element.clientWidth, height: element.clientHeight};
		},

		getElementNode: function(node){
			var returnValue = false;
			if(typeof node == 'string'){
				returnValue = document.getElementById(node);
			}
			else if(typeof node == 'object'){
				returnValue = node;
			}
			return returnValue;
		},

		extend: function(sub, base){
			var copy = {};
			for (var property in base)
    			copy[property] = base[property];

    		for(var property in sub)
    			copy[property] = sub[property];

  			return copy;
		}
	}

	var config = {
		getPostUrl: function(){
			var url = (isLive ? 'http://www.hyves.nl' : base_url) + '/hyvesconnect/smartbutton';
			return url;
		},

		getCacheUrl: function(){
			return isLive ? 'http://cache.hyves-static.net' : base_url;
		},

		getDivId: function(){
			return 'hyvesconnect_div';
		},

		getFormId: function(){
			return 'hyvesconnect_form';
		},

		defaults: {
			iconsize: 24
		},

		getFormMethod: function(){
			return 'get';
		},

		getDefaultOptions: function(){
			return this.defaults;
		},

		setDefaultOptions: function(options){
			// only overwrite options that actually exist
			for (var property in this.defaults){
				if(options[property]){
					this.defaults[property] = options[property]
				}
			}
		}
	}

	var main = {
		generic: function(fields, options, node){
			params.push(fields);
			aOption.push(helper.extend(options, config.getDefaultOptions()));

			id = params.length - 1;
			var elem = helper.getElementNode(node);
			var buttonHtml = builder.buildButton(id);
			if(elem){
				elem.innerHTML = buttonHtml;
			}
			else{
				document.write(buttonHtml);
			}
		},

		cleanup: function(){
			var div = document.getElementById(config.getDivId());
			if(div){
				var up = div.parentNode;
				up.removeChild(div);
			}
		}
	}

	// these methods will be exposed
	return {
		tip: function(fields, options, node){
    		fields['type'] = HYVES_TYPE_TIP;
			main.generic(fields, options, node);
    	},

    	blog: function(fields, options, node){
    		fields['type'] = HYVES_TYPE_BLOGITEM;
    		main.generic(fields, options, node);
    	},

    	widget: function(fields, options, node){
    		fields['type'] = HYVES_TYPE_WIDGET;
    		main.generic(fields, options, node);
    	},

    	interest: function(fields, options, node){
    		fields['type'] = HYVES_TYPE_HUBINTEREST;
    		main.generic(fields, options, node);
    	},

    	hub: function(fields, options, node){
    		fields['type'] = HYVES_TYPE_HUB;
    		main.generic(fields, options, node);
    	},

    	submit: function(id){
			main.cleanup();
    		builder.insertIFrame(id);
    		builder.insertForm(id);
    	},

    	close: function(){
    		main.cleanup();
    	},

    	defaults: function(options){
    		config.setDefaultOptions(options);
    	}
	}
}();
