/*  webs_common.js - global utility functions for use on user sites
 *
 *  @Author: Ryan McGrath
 *  @Requires: No external libraries
 */


if(typeof webs === "undefined") var webs = {};
if(typeof webs.props === "undefined") webs.props = {};


webs.props.devMode = (function() {
    var url = document.location.href.toLowerCase();
    return url.indexOf('local.members.webs.com') >= 0
            || url.indexOf('qa.members.webs.com') >= 0
            || url.indexOf('staging.members.webs.com') >= 0
            || url.indexOf('localhost') >= 0
            || url.indexOf('127.0.0.1') >= 0;
})();


webs.props.adminMode = (function() {
    var url = document.location.href;
    if (!webs.props.devMode) {
        return url.indexOf('members.webs.com') >= 0
    } else {
        return url.indexOf('manageapp') >= 0 || url.indexOf('/Members/') >= 0;
    }
})();


webs.props.baseDomain = (function(){
    var endOfHost = document.location.href.indexOf('/',10);
    var hostName = document.location.href.substring(0,endOfHost) + '/';
    var domainName;

    if (hostName.indexOf('freewebs.com') >= 0) {
        var nextSlash = document.location.href.indexOf('/',endOfHost+1);
        domainName = document.location.href.substring(0,nextSlash) + '/';
    } else {
        domainName = hostName;
    }

    if (webs.props.devMode && !webs.props.adminMode) {
        var pathArr = document.location.pathname.split('/');
        domainName += pathArr[1] + '/';
    }
   return domainName;
})();


webs.props.appsBase = (function(){
    if (webs.props.adminMode) {
        return webs.props.baseDomain + 'manageapp/';
    } else {
        return webs.props.baseDomain + 'apps/';
    }
})();


webs.$ = function(expr) {
	if(typeof jQuery !== "undefined") {
		return jQuery(expr);
	} else {
		/*	If it's an ID, don't filter through anything else. */
		if(/#/.test(expr)) return document.getElementById(expr.replace("#", ""));

		/*	If they provide a class name... */
		if(/\./.test(expr)) {
			/*	The true Array that we'll eventually return. Native implementations return a NodeList,
				which can be less than desireable to work with.
			*/
			var nodeArray = [];

			/*	querySelectorAll - IE8, Safari, Chrome, Moz, Opera, etc... */
			if(!!document.querySelector) {

				var classes = document.querySelectorAll(expr);
				for(var i = 0; i < classes.length; i++) nodeArray.push(classes.item(i));

			/*	Native getElementsByClassName - older Safari/Mozilla/Opera/etc */
			} else if(!!document.getElementsByClassName) {

				var classes = document.getElementsByClassName(expr.replace(".", ""));
				for(var i = 0; i < classes.length; i++) nodeArray.push(classes[i]);

			/*	XPath - if a browser supports it, it's still faster than walking the DOM. ;P */
			} else if(!!document.evaluate) {

			    var query = document.evaluate(
					".//*[contains(concat(' ', @class, ' '), ' " + expr.replace(".", "") + " ')]",
					document,
					null,
					XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
					null
				);
			    for(var i = 0; i < query.snapshotLength; i++) results.push(query.snapshotItem(i));

			/*	Fallback full DOM traversal for annoyingly outdated browsers. */
			} else {

				var els = document.getElementsByTagName("*"),
					elsLength = els.length,
					pattern = new RegExp("^|\\s)" + expr.replace(".", "") + "(\\s|$)");

				for(var i = 0; i < elsLength; i++) {
					if(pattern.test(els[i].className)) nodeArray.push(els[i]);
				}
			}

			return nodeArray;
		}
	}
};

/* javascript loader */
webs.load = {
	_install: function(src, singular, callback) {
		var newScript = document.createElement("script");
		newScript.type = "text/javascript";
		if(singular) newScript.setAttribute('async', 'true');
		newScript.src = src;

		if(typeof callback === "function") {
			if(newScript.readyState) {
				newScript.onreadystatechange = function() {
					if(/loaded|complete/.test(newScript.readyState)) {
						newScript.onreadystatechange = null;
						callback();
					}
				}
			} else {
				newScript.addEventListener("load", callback, false);
			}
		} else if(typeof callback === "string") {
			newScript.src = newScript.src + (/\?/.test(src) ? "&" : "?") + "callback=" + callback;
		}

		document.documentElement.firstChild.appendChild(newScript);
	},

	script: function(src, callback) {
		if(typeof src === "string") webs.load._install.apply(window, [src, true, callback]);
		else {
			for(var i = 0; i < src.length; i++) {
				if(i === src.length -1 && typeof callback === "function") webs.load._install(src[i], false, callback);
				else webs.load._install(src[i], false);
			}
		}
	}
};

webs.loadEvent = function(func) {
    // Try for for jQuery's document.ready availability
	if(typeof jQuery !== "undefined") jQuery(document).ready(func);
    else if(typeof FastInit !== "undefined" && typeof FastInit.addOnLoad === "function") FastInit.addOnLoad(func);
    else webs.fallbackLoadEvent(func);
};

webs.fallbackLoadEvent = (function() {
    var load_events = [], load_timer, script, done, exec, old_onload,

	init = function () {
        done = true;
		clearInterval(load_timer);
        for(i = 0; i < load_events.length; i++) {
		    exec = load_events.shift();
            exec();
		}
        if(script) script.onreadystatechange = '';
	};

	return function(func) {
	    if(done) return func();

        if(!load_events[0]) {
			if(document.addEventListener) document.addEventListener("DOMContentLoaded", init, false);

			/*@cc_on @*/ /*@if (@_win32)
				document.write("<scr"+"ipt id=__ie_onload_webs defer src=//0><\/scr"+"ipt>");
				script = document.getElementById("__ie_onload_webs");
				script.onreadystatechange = function() {
					if (this.readyState == "complete") init();
				};
			/*@end @*/

			if(/WebKit/i.test(navigator.userAgent)) {
				load_timer = setInterval(function() {
					if(/loaded|complete/.test(document.readyState)) init();
				}, 10);
			}

			old_onload = window.onload;
			window.onload = function() {
				init();
				if (old_onload) old_onload();
			};
		}
		load_events.push(func);
	}
})();

webs.siteLoginPopover = function(server, email, siteID) {
	return new Popover(server + '/s/login/siteLoginPopover?id=' + email + '&site=' + siteID, {
		width: 430,
		height: (typeof acsLink !== "undefined" ? 300 : 175),
		heading: 'Manage Website'
	}).show();
};

