/** 
 * N2 library - Utilities  
 * (dependant on YUI 2.x)
 * 
 * Copyright (c) north2. All rights reserved.
 * Code licensed under the BSD Licence
 *
 * @author: Alan Kralj (alan@north2.net)
 * @version: 1.1.7 (08.08.11)
 */


if (typeof(N2) === 'undefined')
	var N2 = {};

if (!console) {
    var console = {log: function(){}};
}

N2.util = {
	createElement: function(type, properties) {
		var obj = document.createElement(type);
		
		for (var id in properties) {
			if (properties[id] != null) {
				if (id == 'className') 
					YAHOO.util.Dom.addClass(obj, properties[id]);
				else if (id == 'type')
					obj.setAttribute('type', properties[id]);
				else if (id == 'name')
					obj.setAttribute('Name', properties[id]);
				else if ((id == 'checked' || id == 'CHECKED') && properties[id] == true)
					obj.setAttribute(id, 'checked');
				else 
					obj[id] = properties[id];
			}		
		}
		
		return obj;
	},
	
	cloneObject: function(obj) {
		var newObj = {};
		
		if (!obj || obj==null) {
			return null;
		}
		
		var clone = function(properties, parent) {
			for (var a in properties) {
				if (YAHOO.lang.isArray(properties[a])) {
					parent[a] = [];
					clone(properties[a], parent[a]);
				}
				else if (YAHOO.lang.isFunction(properties[a])) {
					parent[a] = properties[a];
				}
				else if (YAHOO.lang.isObject(properties[a])) {
					parent[a] = {};
					clone(properties[a], parent[a]);
				}
				else {
					parent[a] = properties[a];
				}
			}
		}
		
		clone(obj, newObj);
		return newObj;
	},
	
	removeFlashObjects: function(container, className) {
		var container = (container) ? document.getElementById(container) || container : document.body;
		var objects;
		var dummy;
		var h;
		var w;
		
		if (className) {
			objects = YAHOO.util.Dom.getElementsByClassName(className, 'object', container);
		}
		else {
			objects = container.getElementsByTagName('object');
		}
		
		for (var a=0; a<objects.length; a++) {
			h = objects[a].getAttribute('height');
			w = objects[a].getAttribute('width');
			
			dummy = N2.util.createElement('div', {className: 'swfdummy'});
			YAHOO.util.Dom.setStyle(dummy, 'width', w + 'px');
			YAHOO.util.Dom.setStyle(dummy, 'height', h + 'px');
			
			YAHOO.util.Dom.insertAfter(dummy, objects[a]);
			YAHOO.util.Dom.setStyle(objects[a], 'display', 'none');
		}
	},
	
	sendRequest: function(uri, params, callback, options) {
		var xhrCallback;
		var options = options || {};
		var failureCallback = (options && options.onfail) ? options.onfail : N2.util.requestFailed;
		
		if (options.indicator) {
			N2.status.startLoadingStatus(options.indicator);
		}

		xhrCallback = {
			success: N2.util.processResponse,
			upload: N2.util.processResponse,
			failure: failureCallback,
			scope: N2,
			argument: [callback, options]
		};
			
		if (options.method=='POST') {
			YAHOO.util.Connect.asyncRequest('POST', uri, xhrCallback, params);
		}
		else {
			if (params) {
				uri += (uri.search(/\?/)>=0) ? '&' : '?';
				uri += params;
			}
			
			YAHOO.util.Connect.asyncRequest('GET', uri, xhrCallback);
		}
	},
	
	processResponse: function(o) {
		var callback = o.argument[0];
		var options = o.argument[1];
		var indicator = options.indicator;
		
		if (indicator) {
			N2.status.stopLoadingStatus(indicator);
		}
		
		if (options.historyUrl && N2.history.ready) {
			N2.history.locked = true;
			YAHOO.util.History.navigate(N2.history.object, options.historyUrl);
		}
		
		callback(o);
	},
	
	// request failure callback
	requestFailed: function(o) {
		// do nothing atm	
		console.log('f41L!');
	},
	
	getTimestamp: function() {
		var now = new Date();
		
		return now.getTime();
	},
	
	initGoogleAnalytics: function() {
		var links = document.getElementsByTagName('a');
		
		YAHOO.util.Event.addListener(links, 'click', function() {
			if (this.href && this.href!='#') {
				_gaq.push(['_trackPageview', this.href]);
			}
		});
	}
}

N2.status = {
	xhrs: Array,

	createStatusObj: function(el, count) {
		var id = YAHOO.util.Dom.generateId(el, 'xhr_');
		
		this.xhrs[id] = (count == null) ? 1 : count;
		return id;
	},
	
	startLoadingStatus: function(el, count) {
		if (!this.xhrs[el.id])
			this.createStatusObj(el, count);
			
		YAHOO.util.Dom.addClass(el, 'loading');
	},
	
	stopLoadingStatus: function(el) {
		var el = (YAHOO.lang.isString(el)) ? document.getElementById(el) : el;
		
		if (!this.xhrs[el.id])
			return false;
	
		this.xhrs[el.id]--;
		if (this.xhrs[el.id]<=0) {
			this.xhrs[el.id] = null;
			
			YAHOO.util.Dom.removeClass(el, 'loading');
		}
	}
}

N2.history = {
	object : 'page',
	ready: false,
	locked: true,
	
	init: function(object, callback) {
		var frame; 
		var field;
		
		if (!document.getElementById('yui-history-iframe') || !document.getElementById('yui-history-field')) {
			frame= N2.util.createElement('iframe', {id: 'yui-history-iframe', src: '/js/n2/blank.htm'});
			field = N2.util.createElement('input', {id: "yui-history-field", type: 'hidden'});
			
			YAHOO.util.Dom.setStyle(frame, 'position', 'absolute');
			YAHOO.util.Dom.setStyle(frame, 'width', '1px');
			YAHOO.util.Dom.setStyle(frame, 'height', '1px');
			YAHOO.util.Dom.setStyle(frame, 'visibility', 'hidden');
			
			document.body.appendChild(frame);
			document.body.appendChild(field);	
		}
		
		if (object) {
			this.object = object;
		}
		
		var bookmarkedState = YAHOO.util.History.getBookmarkedState(N2.history.object);
		var initState = bookmarkedState || window.location.href;

    	YAHOO.util.History.register(N2.history.object, initState, N2.history.onChange, callback);

	    // Initialize the browser history management library
	    try {
	        YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
			N2.history.ready = true;
	    } catch (e) {
			N2.history.ready = false;
			console.log('failed to init history!')
	    }
		
	    YAHOO.util.History.onReady(function () {
	        N2.history.load();
	    });
	},
	
	onChange: function(state, callback) {
		var bookmarkedState = YAHOO.util.History.getBookmarkedState(N2.history.object);
		
		if ((bookmarkedState || window.location.href.indexOf('#')<0) && N2.history.locked!=true && callback) {
			callback(state);
		}
		
		N2.history.locked = false;
	},
	
	load: function(state) {
		var bookmarkedState = YAHOO.util.History.getBookmarkedState(N2.history.object);
		
		if (bookmarkedState) {
			window.location.href = bookmarkedState;
		}
	}
}

