//    base init

// Set global var for IE6 & 7 to save time, space and render speed... 
var _IE6 = false;
var _IE7 = false;
var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
var ie7 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 7.0") != -1);
if (jQuery.browser.msie && ie6) {
	var _IE6 = true;
} else if (jQuery.browser.msie && ie7) {
	var _IE7 = true;
}

(function($) {

    $.base = $.base || {};

    var g_ready = false;
    var g_self = this;
    var omniArr = [];

    $.fn.base = function() {
        return this.each(function() {
            //alert("API method called on " + this);
        });
    };
    
    $.fn.buttonSwap = function(classes) {
    		
		this.each(function() {
			
			// Get/Set vars
			var elem = $(this);
			var buttonText = $(this).attr("value");
			var submitButton = $("<a><span><span><span><span><span>"+buttonText+"</span></span></span></span></span></a>");
			
			submitButton.css({"cursor": "pointer"});
			
			// Add classes if any
			if(classes){
				submitButton.attr("class", classes).addClass("button");
			};
			
			// Set click event for anchor button
			submitButton.click(function(){
				elem.click();
			});
			
			// Hide existing button
			elem.css({"display": "none"});
			// Insert created anchor button
			submitButton.insertAfter(elem);
			
		});
		
    }
    
    $.fn.omniFix = function() {
    
		// the problem here is "this" gets cached/copied, and so even running settimeout to check its state in the DOM wont work as it will only look again at the cached "this"...
		// sooo... how to find the element again... keeping it unique even if passed a classname
		
		var uniqueNum = "unique_" + jQuery.data(this); // we hope this is unique... seems so
		this.attr("unique", uniqueNum)
    
		// oki seems the above should be attepted with an array instead, as the array should store a reference to the object and not copy the object like "this" does
		
		this.find("a").each(function(){
		
			//trace(this)
			//trace(this.onclick)
			
			if(this.onclick == undefined){
				// trace("click event not set yet, send it to reFix for callback") 
				setTimeout(reFix, 500)
			} else {
				// trace("remove click event")
				this.onclick = null;
			}
			
			function reFix() { 
				//trace("find element and send back to omnifix")
				var container = $("*[unique='"+uniqueNum+"']");
				container.omniFix();
			}

		})	
	};

    // I guess this is a bad function to fix a bad design flaw? :¬)
    $.fn.equalHeights = function(firstParent, firstContent, secondParent, secondContent) {
		
		// must have all arguments... 
		if (arguments.length == 4){
		
			//trace($(firstParent).height() + " " + $(secondParent).height())
			
			if(_IE6){
				var min_height = "height";
			} else {
				var min_height = "min-height";
			}
			
			// get differences
			var firstDiff = $(firstParent).height() - $(secondParent).height();
			var secondDiff = $(secondParent).height() - $(firstParent).height();
			
			var firstOffset = $(firstParent).height() - $(firstContent).height()
			var secondOffset = $(secondParent).height() - $(secondContent).height()
			
			//trace(firstDiff + " " + secondDiff);
		
			// If the firstparent is smaller
			if($(firstParent).height() < $(secondParent).height()){
				var setHeight = $(firstContent).css(min_height, $(firstContent).height() + secondDiff);
				var setHeight = setHeight.height();
				//trace("second  " + setHeight + " " + secondOffset)
				$(secondContent).css(min_height, $(secondContent).height())
			// if the firstparent is bigger
			} else if ($(firstParent).height() > $(secondParent).height()){
				var setHeight = $(secondContent).css(min_height, $(secondContent).height() + firstDiff);
				var setHeight = setHeight.height();
				//trace("first  " + firstOffset)
				$(firstContent).css(min_height, $(firstContent).height())
			} // else nada
		};
		
	};
	//$("body").equalHeights(".feed-story-wrap", ".feed-story-rep", ".feed-rss-wrap", ".feed-rss-rep")

    $.base.init = function(options) {
        var c_self = this;
        var c_ready = false;
        c_self.options = $.extend({}, $.base.init.defaults, options);


        c_self.functions = {
            interval: function() {
                /*
                Insert tasks to be repeated at set intervals
                */
                setTimeout(c_self.functions.interval, c_self.options.intervalFrequency);
            },
            initialise: function(context) {
                context.each(function(index) {

                });
            },
            googleAnalytics: function() {
                $.getScript("http://www.google-analytics.com/ga.js", function() {
                    var pageTracker;
                    function startGA() {
                        if (typeof (window['_gat']) != "undefined") {
                            pageTracker = _gat._getTracker("UA-8863485-4"); // new script for base
                            pageTracker._initData();
                            pageTracker._trackPageview();
                        }
                    };
                    setTimeout(startGA, 500);
                });
            },
            configureExternalLinks: function() {
                // Loop through all links that are absolute or with rel="External"
                // Removed http check to protect iframe links and nested content links
                //$("a[rel=\"External\"],a[@href^=http]:not([rel=\"External\"])").each(function() {
                $("a[rel=\"External\"]").each(function() {
                    
                        var anchor = this;
                        if ($(anchor).attr("title") != "") {
                            $(anchor).attr("title", $(anchor).attr("title") + " (opens in a new window)");
                        }
                        else {
                            $(anchor).attr("title", "Opens in a new window");
                        }
                        $(this).click(function() {
                            window.open($(anchor).attr("href"));
                            return false;
                        });
                    
                });
            },
            configureScroll: function() {

				$(".scroller").each(function(){

					// create extra markup for scrollable area
					var container = $("<div></div>").addClass("jsScroll");
					var navigation = $("<div></div>").addClass("navi");
					var naviWrap = $("<div></div>").addClass("naviWrap");
					var prev = $("<div>prev</div>").addClass("prev");
					var next = $("<div>next</div>").addClass("next");
					
					// wrap and reset container var 
					var container = $(this).wrap(container).parent();
					container.prepend(prev).append(next).append(navigation);

					
					// Get lenght of items
					var itemCount = $(this).children(".contents").children("a").length;
					var itemWidth = $(this).children(".contents").children("a:first").width();
					var scrollerWidth = $(this).children(".contents").parent().width();
					var amountPerScroll = Math.floor(scrollerWidth / itemWidth);
					//trace("amountPerScroll " + amountPerScroll);
					//trace("scrollerWidth " + scrollerWidth + " / itemWidth " + itemWidth);

					// Init scroller 
					$(this).scrollable({
						size: amountPerScroll,
						next: '.next',
						prev: '.prev',
						items: '.contents',
						easing: 'easeOutQuart',
						naviItem: 'span',
						speed: 500
					});
					
					prev.dblclick( function () { this.blur();});
					
					// Get width and position navi in the center... surely theres a better way of doing this?
					var naviWidth = (navigation.children().width() -3) * navigation.children().length;
					var naviMargin = Math.round(container.width()/2) - naviWidth
					navigation.css("margin-left", naviMargin)
					
					// add class to container if there is no need to scroll for styling
					if(navigation.children().length <= 1){
						container.addClass("noScroll")
					}
					
				})
				
            },
            configureTabs: function() {
				
				$(".tabs").tabs({ fx: { opacity: 'toggle', height: 'toggle', duration: 'normal' } });
				
            },
            preload: function() {
                c_self.functions.debuglog("preload");
                c_self.functions.preloadImages(
					//["./assets/", "fdsf"]
                );
            },
            preloadImages: function() {
                for (var i = 0; i < arguments.length; i++) {
                    $("<img>").attr("src", arguments[i]);
                }
            }
        };
        c_self.functions.initialise($("body"));
        c_self.functions.googleAnalytics();
        c_self.functions.configureTabs();
        c_self.functions.configureScroll();
        c_self.functions.configureExternalLinks();
        c_ready = true;
    };
    
    // This is quick to type: trace("my console text")
    function trace(logtext) {
		try {
			if (console && console.log) {
				console.log(logtext);
			}
		} catch (err) {
			//alert(err);
		}
	};
    
    // defaults
    $.base.init.defaults = {};

    // initialise one or more instances of the class
    $(document).ready(function() {
        new $.base.init();
        
			// IE6 
			if (_IE6){
				$('body').pngFix();
			};
		$(".ui-tabs-nav").omniFix();
    });
})(jQuery);
