/* Search stuff */

function addSearchEngine()
{
   window.external.AddSearchProvider("http://www.ents24.com/web/ents24search2.xml");
}	

function addSearchLink()
{
	if (window.external && ("AddSearchProvider" in window.external)) 
	{
		document.getElementById('sPlugin').innerHTML =
			'<div style="padding-left:10px;"><font style="color:#a00;">NEW: </font><a href="javascript: addSearchEngine();">Add Ents24 to my<br />browser\'s search engines</a></div>';		
	}
}

/* char counter */

jQuery.fn.charCounter = function(o) {
    
    this.each(function(){
        this._charCounter = new charCounterFn(this, o);
    });
}

var charCounterFn = function(obj, o) {
    if (!o) o={};
    obj.maxChars                =   o.maxChars || 500;
    obj.append                  =   o.append || "";
    obj.prepend                 =   o.prepend || "";
    obj.countDirection          =   o.countDirection === "up"? "up" : "down";

    // get current number of characters  
    var length = $(obj).val().length;  
    
    if (obj.countDirection === "down") {
        var remaining = obj.maxChars - length;
        obj.normalColor = $(obj).parent().find('.charCounter').css('color');
        var clr = (remaining < 0)? "#e33" : obj.normalColor;
        length = remaining;
    } else {
        var clr = $(obj).parent().find('.charCounter').css('color');
    }
     
    // update characters  
    $(obj).parent().find('.charCounter').css({color: clr}).html( obj.prepend+length+obj.append );  
    // bind on key up event  
    $(obj).keyup(function(){  
        // get new length of characters  
        var length = $(obj).val().length;  
        if (obj.countDirection === "down") {
            var remaining = obj.maxChars - length;
            var clr = (remaining < 0)? "#e33" : obj.normalColor;
            length = remaining;
        } else {
            var clr = $(obj).parent().find('.charCounter').css('color');
        }
        // update  
        $(obj).parent().find('.charCounter').css({color: clr}).html( obj.prepend+length+obj.append );  
    });  
    
}

/* popup window */

function NewWindow(mypage, w, h, scroll) {
	        
    var sw = screen.width;
    var sh = screen.height;
    
    if(navigator.userAgent.indexOf("Opera") != -1){ // opera get s positioning wrong
        sw = innerWidth;
        sh = innerHeight;
    }
    
    if (h > sh) {
        h = (sh - 20);
    }

    var winl = (sw - w) / 2;
    var wint = (sh - h) / 2;

    winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'
    win = window.open(mypage, 'Ents24 Info Window', winprops)
    if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
    return false;
}

/* old jquery utils */

function getRef(obj){
	var objclass = $(obj).attr("class");
	// if this element has more than one class, just use the first one
	if(objclass.indexOf(" ") != -1){
		objclass = objclass.substr(0, objclass.indexOf(" "));
	}
	var objid = $(obj).attr("id");
	return objid.substr(objclass.length);
}

function getFullPath(filename){
	return ("http://" + location.hostname + "/web/" + filename);
}

/* fadeIn/Out IE fix */

(function($) {
	$.fn.fixFadeIn = function(speed, callback) {
		$(this).fadeIn(speed, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
		return $(this);
	};
	$.fn.fixFadeOut = function(speed, callback) {
		$(this).fadeOut(speed, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
		return $(this);
	};
	$.fn.fixFadeTo = function(speed, opacity,  callback) {
		$(this).fadeTo(speed, opacity, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
		return $(this);
	};
})(jQuery);

/* JS Template object for displaying HTML without hidden text */

var jsTemplate = function(tmpID, HTML, params) {
    this.id = tmpID;
    this._html = HTML;
    this.params = params;
    this.onshow = null;
    this.onhide = null;
};

jsTemplate.prototype = {
    show: function(speed) {
        if (this.params.behaviour === "insert") {
            var insertClass = this.params.insertClass || "jsTmp-"+this.id;
            var self = this;
			console.log($("."+insertClass).length);
            $("."+insertClass).append($(this._html)).filter(":hidden").show(speed);
			$(".toggleWith-"+this.id).toggle(speed); 
            
        } else if (this.params.behaviour === "replace") {
            var insertClass = this.params.insertClass || "jsTmp-"+this.id;

            $("."+insertClass).html(this._html).filter(":hidden").show(speed);
            $(".toggleWith-"+this.id).toggle(speed); 
            
        } else if (this.params.behaviour === "modal") {
            openDialog(this._html);
        }
        if (typeof this.onshow === "function") {
        	this.onshow();
        }
    },
    hide: function(speed) {
        if (this.params.behaviour === "modal") {
            closeDialog();
        } else {
            var insertClass = this.params.insertClass || "jsTmp-"+this.id;
            if ($("."+insertClass).children().filter(":visible").length > 0) {
                $("."+insertClass).hide(speed); 
                $(".toggleWith-"+this.id).toggle(speed); 
            }
        }  
        if (typeof this.onhide === "function") {
        	this.onhide();
        }
    },
    html: function() {
        return this._html;
    }
};

window.preLoadedIms = {};

var jsTemplateStore = {
    store: {},
    globalsRead: false,
    readTemplates: function() {
        if (!this.globalsRead && window.jsTemplates) {
            for (var tmpID in window.jsTemplates) {
                this.add(tmpID, window.jsTemplates[tmpID].html, 
                            window.jsTemplates[tmpID].params);
            }
            this.globalsRead = true;
        }
    },
    get: function(tmpID){
        this.readTemplates();
        return this.store[tmpID];
    },
    add: function(tmpID, tmpHTML, params){
        this.store[tmpID] = new jsTemplate(tmpID, tmpHTML, params);
        
        // pre load any images found
        $(tmpHTML).find("img").each(function(){
        	if ($(this).attr('src') && window.preLoadedIms[$(this).attr('src')] === undefined) {
        		window.preLoadedIms[$(this).attr('src')] = new Image();
        		window.preLoadedIms[$(this).attr('src')].src = $(this).attr('src');
        		//console.log("Preloaded image "+$(this).attr('src'));
        	}
        });
        
        // check if template had been displayed manually
    },
    show: function(tmpID, speed) {
        var tmp = this.get(tmpID);
        if (tmp) {
            tmp.show(speed);
        }
    },
    hide: function(tmpID, speed) {
        if (!tmpID) {
            // hide all
            this.readTemplates();
            for (var id in this.store) {
                this.store[id].hide(speed);
            }
        }
        var tmp = this.get(tmpID);
        if (tmp) {
            tmp.hide(speed);
        }
    }
};

/* create nice popup from any div */

function openDialog(selector) {
    var dialogHTML = '<div id="ents_dialogCont" style="display:none">'
            +'<div id="ents_dialogBorder">'
                +'<div id="ents_dialog">'
                +'</div>'
                +'<a href="#" id="ents_dialogClose" onclick="closeDialog(); return false;">Close</a>'
            +'</div>'
        +'</div>'
        +'<div id="ents_dialogOverlay" style="display:none"></div>';
    
    $("a,input,textarea,button,select", $('body')).bind('focus', preventFocus);
    
    $(dialogHTML).appendTo($('body'));
    $(selector).clone().appendTo($("#ents_dialog"));
    
    $("#ents_dialogOverlay").show();
    $("#ents_dialogCont").show();
    
    /* postion dialog properly */
    var height = $("#ents_dialogBorder").height() 
        + parseInt($("#ents_dialogBorder").css('paddingTop'))
        + parseInt($("#ents_dialogBorder").css('paddingBottom'));
    var marginTop = ($(window).height() - height) /2;
    //console.log("h: "+height+" window: "+$(window).height()+" margin: "+marginTop);
    $("#ents_dialogBorder").css('marginTop', $(window).scrollTop()+marginTop+'px');
    if($.browser.msie && $.browser.version < 7) {
        $("#ents_dialogOverlay").height($(document).height()+'px');
    }

}

function preventFocus() {
    this.blur();
}

function closeDialog() {
    $("#ents_dialogCont").remove();
    $("#ents_dialogOverlay").remove();
    $("a,input,textarea,button,select", $('body')).unbind('focus', preventFocus);
}

function showSubMenu(tabID) {
    clearTab(tabID); 
    clearTimeout(window.subMenuTimer);
    var active = getActiveTab();
    
    if (tabID) {
        window.subMenuShowing = tabID;
        if (active && active !== tabID) {
            $("#nav-"+active+" a").css({backgroundPosition: "0 -110px", zIndex: 2});
        }
        var subHTML = jsTemplateStore.get("subMenu-"+tabID);
        if (subHTML) {
            subHTML.show();
            $("#subMenuCont").find("a").click(function(){
            	window.loadingNextPage = true;
            });
            setupDropDowns();
            return true;
        } else {
            //show nothing
            if ($("#subMenuCont").hasClass('subMenuFloating')) {
                $("#subMenuCont").html("");
            } else {
                $("#subMenuCont").find(".mask").remove();
                $("#subMenuCont").append($('<div class="mask"></div>').css({
                    width: "100%",
                    height: "41px",
                    backgroundColor: "#fff",
                    position: "absolute",
                    top: "0px",
                    left: "0px",
                    zIndex: "50"
                }).fadeTo(0, 0.5));
            }
            return true;
        }
    }
    // not shown anything so default to active tab if there is one
    
    $("#nav-"+active+" a").css({backgroundPosition: "0 -55px", zIndex: 3});
    
    if (active) {
        window.subMenuShowing = active;
        var subHTML = jsTemplateStore.get("subMenu-"+active);
        if (subHTML) {
            subHTML.show();
            $("#subMenuCont").find("a").click(function(){
            	window.loadingNextPage = true;
            });
            setupDropDowns();
            return true;
        }
    }
    window.subMenuShowing = false;
    //still not shown anything so hide submenu
    $("#subMenuCont").html("");
    setupDropDowns();
}

function getActiveTab() {
    var classes = $("#nav").attr("class").split(" ");
    var activeID = false;
    for (var i in classes) {
        if (classes[i].substr(0, 4) == "nav-") {
            return classes[i].substr(4);
        }
    }
    return false;
}

function clearTab(tabID) {
    if (window.subMenuShowing && window.subMenuShowing !== tabID) {
        $("#nav-"+window.subMenuShowing+" a").css({backgroundPosition: "0 0", zIndex: 1});
    }
}

function delayedClear() {
    window.subMenuTimer = setTimeout(function(){
        if (window.protectSub) {
            return;
        }
        clearTab(); 
        showSubMenu(null);
    }, 500);
}

function hoverIntentOptions(over, out, o) {
    if (!o) o = {};
    this.over = over;
    this.out = out;
    this.sensitivity = o.sensitivity || 3;
    this.interval = o.interval || 50;
    this.timeout = o.timeout || 0;
	
	if (isIE6()) {
		this.sensitivity = 7;
		this.interval = 100;
	}
}

function getDropDownTmpID(el) {
    var classes = $(el).parent().attr("class").split(" ");
    var dropDownTmpID = false;
    for ( var i in classes) {
        if (classes[i].substr(0, 12) === "dropDownTmp-") {
            dropDownTmpID = classes[i].substr(12);
        }
    }
    return dropDownTmpID;
}

function isIE6() {
	return ($.browser.msie && $.browser.version < 7);
}

window.counter = 0;

function setupDropDowns() {
    var townHover = new hoverIntentOptions(function(){
        var dropDownTmpID = getDropDownTmpID(this);
        
        if ( $(".dropCont-"+dropDownTmpID).length > 0) {
            $(".dropCont-"+dropDownTmpID).show();
        } else {
            var tmp = jsTemplateStore.get(dropDownTmpID);
            $(tmp.html()).addClass("dropCont-"+dropDownTmpID).appendTo($('body'));
            
            // work out where to put it
            var offset = $(this).offset();
            offset.left += $(this).parent().width() + 10;
            offset.left -= $(".dropCont-"+dropDownTmpID).outerWidth();
            
            $(".dropCont-"+dropDownTmpID).css("left", offset.left+"px").hover(function(){
                window.protectSub = true;
                window.protectDropDown = true;
            },function(){
                $(".dropCont-"+dropDownTmpID).hide();
                window.protectSub = false;
                window.protectDropDown = false;
                clearTab(); 
                showSubMenu(null);
            });
        }
    },
    function(){
        var dropDownTmpID = getDropDownTmpID(this);
        window.dropDownTimer = setTimeout(function(){
            if (window.protectDropDown) {
                return false;
            }
            $(".dropCont-"+dropDownTmpID).hide();
        }, 200);
    });
    
    $(".dropdown a").hoverIntent(townHover).click(function(){return false});
}

function setFieldDefault(el) {
	var defaultVal = getFieldDefault(el);
	
	if ( ! defaultVal) {
		return;
	}
	
	if ( ! $(el).hasClass('default-val') && $(el).val() === '') {
		$(el).val(defaultVal).addClass('default-val');
	}
}

function clearFieldDefault(el) {
	if ($(el).hasClass('default-val')) {
		$(el).val('').removeClass('default-val');
	}
}

function getFieldDefault(el) {
	return $('#'+$(el).attr('name')+'-default').val();
}

$(function(){
    // SUB MENUS
    
    window.subMenuTimer = null;
    window.protectSub = false;
    
    var menuHover = new hoverIntentOptions(function(){
        var id = $(this).parent().attr("id").substr(4);
        clearTimeout(window.subMenuTimer);
        $(this).css({backgroundPosition: "0 -55px", zIndex:5});
        showSubMenu(id);
    },
    delayedClear);
    
    $("#nav a").hoverIntent(menuHover);
    
    window.loadingNextPage = false;
    
    $("#subMenuCont").hover(function(){
        if ($(this).find(".mask").length < 1) {
            window.protectSub = true;
        }
    }, function(){
    	if (window.loadingNextPage) {
    		return;
    	}
        window.protectSub = false;
        delayedClear();
    });
    
    window.protectDropDown = false;
    setupDropDowns();
    
    // automatically find links to showHide templates
    $("a").each(function(i){
        if($(this).attr("href")){
            var tmpID = $(this).attr("href").match(/jsID=[^&]+/);
            
            if (tmpID) {
                tmpID = tmpID[0].substr(5);
				// if link has hoverActivate class make it happen on hover
				if ($(this).hasClass('hoverActivate')) {
					$(this).hover(function(){
						$(this).parent().siblings().removeClass('selected');
						
						$(this).parent().addClass('selected');
	                    jsTemplateStore.show(tmpID);
	                    return false;
					});
				}
				else 
				{
					$(this).click(function(){
	                    jsTemplateStore.show(tmpID);
	                    return false;
	                });
				}
	                
            } else {
                var hideInd = $(this).attr("href").indexOf("#hide");
                if (hideInd > -1) {
                    $(this).click(function(){
                        jsTemplateStore.hide();
                        return false;
                    });
                }
            }
    	} 
    });
    
    // when changetown dialog is shown, set up event loading handler
    window.jsTemplateStore.get('changeTown').onshow = function() {
    	$("#changeTownDialog a").click(function(){
    		window.jsTemplateStore.get('ents-loading').show();
			return true;
    	});
		// IE 6 just can't do this...
		if ( ! $.browser.msie || ( $.browser.msie && $.browser.version >= 7) ) {
			$("#changeTownDialog form").submit(function(){
	    		window.jsTemplateStore.get('ents-loading').show();
	    	});
		}
    };
    // if changeTown has been manually displayed by page, trigger onshow()
    if ($("#changeTownDialog").length > 0) {
    	window.jsTemplateStore.get('changeTown').onshow();
    }
	// IE 6 hack for loading animation display
	if ($.browser.msie && $.browser.version < 7) {
		window.jsTemplateStore.get('ents-loading').params.behaviour = 'replace';
	}
	
	// setup default value substitution for form fields
	$('input[type=text]').each(function(){
		if (getFieldDefault(this)) {
			setFieldDefault(this);
			$(this).focus(function(){
				clearFieldDefault(this);
			}).blur(function(){
				setFieldDefault(this);
			}).bind('keypress', function(){
				// This is to catch the case that the user focused the box before document.ready
				// But didnt type anything so they are now focussed on the field with the default class
				// and the default string before their cursor
				if ($(this).hasClass('default-val')) {
					$(this).val($(this).val().replace(getFieldDefault(this), '')).removeClass('default-val');
				}
			});
		}
	});
	
	// Date pickers
	$("input[type=text].datePicker").datepicker({
		dateFormat: 'dd/mm/yy',
		mandatory: true,
		firstDay: 1,
		minDate: 0,
    	maxDate: 365,
    	changeMonth: false,
    	changeYear: false,
    	prevText: '< month',
    	nextText: 'month >',
    	numberOfMonths: 1
    });
});
