﻿

$(document).ready(function () {


    // Service - Arrows


    // $('div.service').hoverIntent(menuIn, menuOut);


    //    $("div.service").mouseover(function () {
    //        $(this).removeClass('service')
    //        $(this).addClass('serviceBackground')
    //    });

    //    $("div.service").mouseout(function () {

    //        $(this).removeClass('serviceBackground')
    //        $(this).addClass('service')
    //    });

    // Sales Nav
    //Default Action
    $(".salesContent").hide(); //Hide all content
    $("ul.tabs li:first a").addClass("activeSales").show(); //Activate first tab
    $(".salesContent:first").show(); //Show first tab content




    // Video Nav
    //Default Action
    $(".mainVideo").hide(); //Hide all content
    $("ul.tabs2 li:first a").addClass("activeVideo").show(); //Activate first tab
    $(".mainVideo:first").show(); //Show first tab content






    //    // Open/Close Widget

    //    $("div.widgetHPTitle").click(function() {

    //    var temp = $(this).parent().find("div.widgetHPContent");
    //        temp.toggleClass("open");
    //    });



    // Start - Vertical Nav

    //    $("div.verticalNav ul li a").click(function () {

    //        $("div.verticalNavOpen").removeClass("open");
    //        $("div.verticalNavOpen").addClass("faqClose")
    //        $("div.verticalNav ul li").removeClass("active")
    //        $(this).parent().toggleClass("active");
    //        var temp2 = $(this).parent().find("div.verticalNavOpen");
    //        temp2.toggleClass("open");
    //    });

    // End - Vertical Nav




    // Start - Open FAQ

    $("div.faq ul li a").click(function () {

        $(this).parent().toggleClass("faqOpen");
        var temp2 = $(this).parent().find("div.faqInline");
        // $("div.faqInline").addClass("close");

        // temp2.toggleClass("open");
        if ($(temp2).attr('class') == 'faqInline close')
            $(temp2).attr('class', 'faqInline open')
        else
            $(temp2).attr('class', 'faqInline close')
    });

    // Open / Close All - FAQ 
    $("div.faqBorder a.openAll").click(function () {
        $(this).parent().parent().find("div.faqInline").removeClass("close");
        $(this).parent().parent().find("div.faqInline").addClass("open");
        $(this).parent().parent().find("ul > li").addClass("faqOpen");
    });
    $("div.faq a.openAll").click(function () {

        $(this).parent().find("div.faqInline").removeClass("close")
        $(this).parent().find("ul> li").addClass("faqOpen")
        $(this).parent().find("div.faqInline").addClass("open")
    });

    $("div.faqBorder a.closeAll").click(function () {
        $(this).parent().parent().find("div.faqInline").removeClass("open");
        $(this).parent().parent().find("ul > li").removeClass("faqOpen");
        $(this).parent().parent().find("div.faqInline").addClass("close");
    });
    $("div.faq a.closeAll").click(function () {

        $(this).parent().find("div.faqInline").removeClass("open")
        $(this).parent().find("ul> li").removeClass("faqOpen")
        $(this).parent().find("div.faqInline").addClass("close")
    });

    // End - Open FAQ


    // Weekly Rating Widget

    $(".clickableRating").click(function () {
        $(this).next("div").slideToggle("slow")
	  .siblings("div:visible").slideUp("slow");
        $(this).toggleClass("active");
        $(this).siblings(".clickableRating").removeClass("active");
    });





    // Widget

    function widgetIn() {
        $(this).addClass('widgetOver')
        var $titleBackground = $(this).find('div.widgetHPTitle, div.widgetTitle');
        $titleBackground.css({ background: "#c90000" });
        var $title = $(this).find('div.widgetHPTitle h2, div.widgetTitle h2');
        $title.removeClass('widgetTitleOut');
        $title.addClass('widgetTitleOver');
    }


    function widgetOut() {
        $(this).removeClass('widgetOver')
        var $titleBackground2 = $(this).find('div.widgetHPTitle, div.widgetTitle');
        $titleBackground2.css({ background: "#F2F2F2" });
        var $title2 = $(this).find('div.widgetHPTitle h2, div.widgetTitle h2');
        $title2.removeClass('widgetTitleOver');
        $title2.addClass('widgetTitleOut');
    }


    $('div.widgetHP, div.widget').hoverIntent({

        sensitivity: 7,   // number = sensitivity threshold (must be 1 or higher)
        interval: 0,    // number = milliseconds of polling interval
        over: widgetIn,   // function = onMouseOver callback (required)
        timeout: 0,       // number = milliseconds delay before onMouseOut function call
        out: widgetOut    // function = onMouseOut callback (required)

    });

    //    $('div.widgetHP, div.widget').mouseover(function () {

    //        $(this).addClass('widgetOver')
    //        var $titleBackground = $(this).find('div.widgetHPTitle, div.widgetTitle');
    //        $titleBackground.css({ background: "#c90000" });
    //        var $title = $(this).find('div.widgetHPTitle h2, div.widgetTitle h2');
    //        $title.removeClass('widgetTitleOut');
    //        $title.addClass('widgetTitleOver');
    //    });

    //    $('div.widgetHP, div.widget').mouseout(function () {

    //        $(this).removeClass('widgetOver')
    //        var $titleBackground2 = $(this).find('div.widgetHPTitle, div.widgetTitle');
    //        $titleBackground2.css({ background: "#F2F2F2" });
    //        var $title2 = $(this).find('div.widgetHPTitle h2, div.widgetTitle h2');
    //        $title2.removeClass('widgetTitleOver');
    //        $title2.addClass('widgetTitleOut');
    //    });

    // Tonight - Background Widget


    //On Click Event
    $("ul.tabs2 li a").click(function () {
        $(".positionAbsoluteVideo").hide();
        $(".positionAbsoluteVideoImage").show();
        $(".text_container").show();
        $(".playPic").show();
        $(".background_container").show();
        $("ul.tabs2 li:first a").removeClass("activeVideo");
        $("ul.tabs2 li a").removeClass("activeVideoTab"); //Remove any "active" class
        $(this).addClass("activeVideoTab"); //Add "active" class to selected tab
        $(".mainVideo").hide(); //Hide all tab content        
        var activeTab = $(this).attr("href"); //Find the rel attribute value to identify the active tab + content
        $(activeTab).show(); //Fade in the active content, U can also change the: fadeIn() to show()
        return false;
    });


    $(".playPic").click(function () {
        $(this).hide();
        $(".positionAbsoluteVideoImage").show();
    });

    /* $(".playPicInline").click(function () {
    $(this).hide();
    $("#" + $(this).attr("rel")).attr("src") = $("#" + $(this).attr("rel")).attr("src").replace("as=0","as=1");
    });*/

    //    $('select#comboChannel option').css("color", "#000");
    //    $('select#comboChannel option[select=""]').css("color", "#c90000");
    //    $('select#comboChannel option[select=""]').attr("style", "color:#c90000");




    /**/

});








function setHomepage(url, errMsg) {
    if (document.all) {
        document.body.style.behavior = 'url(#default#homepage)';
        document.body.setHomePage(url);

    }
    else if (window.sidebar) {
        if (window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            }
            catch (e) {
                alert(errMsg);
            }
        }
        var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
        prefs.setCharPref('browser.startup.homepage', url);
    }
}


//send resume for checked position
function SendCheckedNewPosion(urlPrefix) {
    var ids = '';
    $("input.chkNewPosion").each(function () {
        if ($(this).attr('checked')) {
            if (ids != '')
                ids += ",";

            ids += $(this).attr('rel')

        }
    });

    if (ids != '') {
        window.location = urlPrefix + ids;
    }

}




function PhoneCheck(source, arguments) {
    if (isNaN(arguments.Value)) {
        arguments.IsValid = false;
    } else {
        arguments.IsValid = true;
    }
}



function IdNumberCheck(source, arguments) {
    if (isNaN(arguments.Value)) {
        arguments.IsValid = false;
    } else {
        arguments.IsValid = true;
    }


    if (arguments.Value.length < 5 || arguments.Value.length > 10)
        arguments.IsValid = false;


}


function CheckNemericValue(e) {
    var key;
    key = e.which ? e.which : e.keyCode;
    if (key >= 48 && key <= 57) {
        return true;
    }
    else {
        //alert("please enter number only");
        return false;
    }
}


 



if (typeof (dd_domreadycheck) == "undefined") //global variable to detect if DOM is ready
    var dd_domreadycheck = false;


var anylinkcssmenu = {

    menusmap: {},
    preloadimages: [],
    effects: { delayhide: 0, fade: { enabled: false, duration: 200} }, //customize menu effects

    dimensions: {},

    getoffset: function(what, offsettype) {
        return (what.offsetParent) ? what[offsettype] + this.getoffset(what.offsetParent, offsettype) : what[offsettype]
    },

    getoffsetof: function(el) {
        el._offsets = {
            left: this.getoffset(el, "offsetLeft"),
            right: this.getoffset(el, "offsetLeft") + el.offsetWidth,
            top: this.getoffset(el, "offsetTop"),
            h: el.offsetHeight,
            w: el.offsetWidth
        }

    },

    getdimensions: function(menu) {

        this.dimensions = { anchorw: menu.anchorobj.offsetWidth, anchorh: menu.anchorobj.offsetHeight,
            docwidth: (window.innerWidth || this.standardbody.clientWidth) - 20,
            docheight: (window.innerHeight || this.standardbody.clientHeight) - 15,
            docscrollx: window.pageXOffset || this.standardbody.scrollLeft,
            docscrolly: window.pageYOffset || this.standardbody.scrollTop
        }
        if (!this.dimensions.dropmenuw) {
            this.dimensions.dropmenuw = menu.dropmenu.offsetWidth
            this.dimensions.dropmenuh = menu.dropmenu.offsetHeight
        }
    },

    isContained: function(m, e) {
        var e = window.event || e
        var c = e.relatedTarget || ((e.type == "mouseover") ? e.fromElement : e.toElement)
        while (c && c != m) try { c = c.parentNode } catch (e) { c = m }
        if (c == m)
            return true
        else
            return false
    },

    setopacity: function(el, value) {
        el.style.opacity = value
        if (typeof el.style.opacity != "string") { //if it's not a string (ie: number instead), it means property not supported
            el.style.MozOpacity = value
            if (el.filters) {
                el.style.filter = "progid:DXImageTransform.Microsoft.alpha(opacity=" + value * 100 + ")"
            }
        }
    },

    showmenu: function(menuid) {

     
        var menu = anylinkcssmenu.menusmap[menuid];
        var generalContainer = document.getElementById("generalMenuList");

        this.getoffsetof(generalContainer);
        this.getoffsetof(menu.anchorobj);
        this.getdimensions(menu);

        var oParent = menu.anchorobj;
        var oChild = menu.dropmenu;

        if (!menu.attached) {
            oParent.appendChild(oChild)
            menu.attached = true

            this.getoffsetof(menu.dropmenu);


            //menu.dropmenu._offsets.left -= this.dimensions.anchorw;

            // menu.dropmenu.style.left = menu.dropmenu._offsets.left + 'px';
            // menu.dropmenu.style.right = menu.dropmenu._offsets.right + 'px';

            if (page_dir != "undefined" && page_dir == "rtl") {
                //alert(menu.dropmenu._offsets.left + "\n" + generalContainer._offsets.left)

                if (menu.dropmenu._offsets.left < generalContainer._offsets.left) {
                    menu.dropmenu.style.marginRight = (this.dimensions.anchorw - this.dimensions.dropmenuw) + 'px'

                }
            }
            else {
                if (menu.dropmenu._offsets.right > generalContainer._offsets.right) {
                    menu.dropmenu.style.marginLeft = (this.dimensions.anchorw - this.dimensions.dropmenuw) + 'px'
                }
            }
        }
        menu.dropmenu.setcss({ visibility: 'visible' })
    },



    setcss: function(param) {
        for (prop in param) {
            this.style[(prop + '').replace('1', '-')] = param[prop]
        }
    },

    setcssclass: function(el, targetclass, action) {
        var needle = new RegExp("(^|\\s+)" + targetclass + "($|\\s+)", "ig")
        if (action == "check")
            return needle.test(el.className)
        else if (action == "remove")
            el.className = el.className.replace(needle, "")
        else if (action == "add" && !needle.test(el.className))
            el.className += " " + targetclass
    },

    hidemenu: function(menuid) {
        var menu = anylinkcssmenu.menusmap[menuid]
        //menu.dropmenu.setcss({visibility:'hidden', left:0, top:0})
        //roi
        //menu.dropmenu.setcss({ visibility: 'hidden' })
    },

    getElementsByClass: function(targetclass) {
        if (document.querySelectorAll)
            return document.querySelectorAll("." + targetclass)
        else {
            var classnameRE = new RegExp("(^|\\s+)" + targetclass + "($|\\s+)", "i") //regular expression to screen for classname
            var pieces = []
            var alltags = document.all ? document.all : document.getElementsByTagName("*")
            for (var i = 0; i < alltags.length; i++) {
                if (typeof alltags[i].className == "string" && alltags[i].className.search(classnameRE) != -1)
                    pieces[pieces.length] = alltags[i]
            }
            return pieces
        }
    },

    addEvent: function(targetarr, functionref, tasktype) {
        if (targetarr.length > 0) {
            var target = targetarr.shift()
            if (target.addEventListener)
                target.addEventListener(tasktype, functionref, false)
            else if (target.attachEvent)
                target.attachEvent('on' + tasktype, function() { return functionref.call(target, window.event) })
            this.addEvent(targetarr, functionref, tasktype)
        }
    },

    domready: function(functionref) { //based on code from the jQuery library
        if (dd_domreadycheck) {
            functionref()
            return
        }
        // Mozilla, Opera and webkit nightlies currently support this event
        if (document.addEventListener) {
            // Use the handy event callback
            document.addEventListener("DOMContentLoaded", function() {
                document.removeEventListener("DOMContentLoaded", arguments.callee, false)
                functionref();
                dd_domreadycheck = true
            }, false)
        }
        else if (document.attachEvent) {
            // If IE and not an iframe
            // continually check to see if the document is ready
            if (document.documentElement.doScroll && window == window.top) (function() {
                if (dd_domreadycheck) return
                try {
                    // If IE is used, use the trick by Diego Perini
                    // http://javascript.nwbox.com/IEContentLoaded/
                    document.documentElement.doScroll("left")
                } catch (error) {
                    setTimeout(arguments.callee, 0)
                    return;
                }
                //and execute any waiting functions
                functionref();
                dd_domreadycheck = true
            })();
        }
        if (document.attachEvent && parent.length > 0) //account for page being in IFRAME, in which above doesn't fire in IE
            this.addEvent(window, function() { functionref() }, "load");
    },

    addState: function(anchorobj, state) {
        if (anchorobj.getAttribute('data-image')) {
            var imgobj = (anchorobj.tagName == "IMG") ? anchorobj : anchorobj.getElementsByTagName('img')[0]
            if (imgobj) {
                imgobj.src = (state == "add") ? anchorobj.getAttribute('data-overimage') : anchorobj.getAttribute('data-image')
            }
        }
        else
            anylinkcssmenu.setcssclass(anchorobj, "selectedanchor", state)
    },


    setupmenu: function(targetclass, anchorobj, pos) {

        this.standardbody = (document.compatMode == "CSS1Compat") ? document.documentElement : document.body
        var relattr = anchorobj.getAttribute("rel")
        var dropmenuid = relattr.replace(/\[(\w+)\]/, '')

        var menu = this.menusmap[targetclass + pos] = {
            id: targetclass + pos,
            anchorobj: anchorobj,
            dropmenu: document.getElementById(dropmenuid),
            revealtype: (relattr.length != dropmenuid.length && RegExp.$1 == "click") ? "click" : "mouseover",
            orientation: anchorobj.getAttribute("rev") == "lr" ? "lr" : "ud"
        }

        menu.anchorobj._internalID = targetclass + pos
        menu.anchorobj._isanchor = true
        menu.dropmenu._internalID = targetclass + pos

        //document.body.appendChild(menu.dropmenu) //move drop down div to end of page
        menu.dropmenu.setcss = this.setcss
        menu.anchorobj.setcss = this.setcss


        this.addEvent([menu.anchorobj, menu.dropmenu], function(e) { //MOUSEOVER event for anchor, dropmenu
            var menu = anylinkcssmenu.menusmap[this._internalID]
            if (this._isanchor && menu.revealtype == "mouseover") {// && !anylinkcssmenu.isContained(this, e)){ //event for anchor
                anylinkcssmenu.showmenu(menu.id)
                anylinkcssmenu.addState(this, "add")
            }

        }, "mouseover")

        this.addEvent([menu.anchorobj, menu.dropmenu], function(e) { //MOUSEOUT event for anchor, dropmenu
            if (!anylinkcssmenu.isContained(this, e)) {
                var menu = anylinkcssmenu.menusmap[this._internalID]
                anylinkcssmenu.addState(menu.anchorobj, "remove")
                anylinkcssmenu.hidemenu(menu.id)

            }
        }, "mouseout")




        this.addEvent([menu.anchorobj, menu.dropmenu], function(e) { //CLICK event for anchor, dropmenu
            var menu = anylinkcssmenu.menusmap[this._internalID]
            if (this._isanchor && menu.revealtype == "click") {
                if (menu.dropmenu.style.visibility == "visible")
                    anylinkcssmenu.hidemenu(menu.id)
                else {
                    anylinkcssmenu.addState(this, "add")
                    anylinkcssmenu.showmenu(menu.id)
                }
                if (e.preventDefault)
                    e.preventDefault()
                return false
            }
            else {
                anylinkcssmenu.hidemenu(menu.id)
            }
        }, "click")

    },

    init: function(targetclass) {

        this.domready(function() { anylinkcssmenu.trueinit(targetclass) })
    },

    trueinit: function(targetclass) {

        var anchors = this.getElementsByClass(targetclass)
        var preloadimages = this.preloadimages



        for (var i = 0; i < anchors.length; i++) {
            if (anchors[i].getAttribute('data-image')) { //preload anchor image?
                preloadimages[preloadimages.length] = new Image()
                preloadimages[preloadimages.length - 1].src = anchors[i].getAttribute('data-image')
            }
            if (anchors[i].getAttribute('data-overimage')) { //preload anchor image?
                preloadimages[preloadimages.length] = new Image()
                preloadimages[preloadimages.length - 1].src = anchors[i].getAttribute('data-overimage')
            }
            this.setupmenu(targetclass, anchors[i], i)
        }
    }

}
var tout = 200;
 function onlyNumbers(evt) {
     //var e = event || evt;
     if (!evt) evt = window.event;

    	var charCode = evt.which || evt.keyCode;
    	if (charCode > 31 && (charCode < 48 || charCode > 57))
    		return false;
    	return true;
    }

    function checkEmailRegExp(email) {
    	var r = new RegExp("^[^!\\.][\\w-\\.]{1,}@([\\w-]+\\.)+[A-Za-z]{2,5}$");
    	var m = r.exec(email);
    	if (m != null && m.length > 0) return true;
    	return false;
    }

    function checkText(text) {
    	if (text.indexOf('<') > -1 || text.indexOf('>') > -1 || text.indexOf('*') > -1)
    		return false;
    	return true;
    }
    function checkAlphaNumeric(text) {
    	var filter = /^[A-Za-z0-9\-\u0591-\u05F4\u0400-\u0450\' ]+$/;
    	if (!filter.test(text)) return false;
    	return true;
    }
    function checkAlpha(text) {
    	var filter = /^[A-Za-z\u0591-\u05F4\u0400-\u0450\' ]+$/;
    	if (!filter.test(text)) return false;
    	return true;
    }
    function trim(str) {
    	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    }

    function checkPasswordRegExp(pass) {
    	if (pass.length < 6 || pass.length > 12)
    		return false;
    	else {
    		var r = /(.)\1\1/;
    		var r2 = /^(?=.*\d)(?=.*[A-Za-z])[A-Za-z0-9]+$/
    		if (!r.test(pass) && r2.test(pass)) 
				return true;
			else
    			return false;
    	}
    }

    function checkEmail(x) {
    	if (x.length < 1) {
    		canGo = false;
    		setTimeout("$('#trEmailReq').show()",tout);
    		setTimeout("$('#trEmail').hide()",tout);
    	}
    	else {
    		setTimeout("$('#trEmailReq').hide()",tout);
    		if (!checkEmailRegExp(x)) {
    			canGo = false;
    			setTimeout("$('#trEmail').show()",tout);
    		}
    		else {
    			setTimeout("$('#trEmail').hide()", tout);
    		}
    	}
    }
    function checkID(x) {
    	if (x.length < 1) {
    		canGo = false;
    		setTimeout("$('#trIDReq').show()",tout);
    		setTimeout("$('#trID').hide()",tout);
    	}
    	else {
    		setTimeout("$('#trIDReq').hide()",tout);

    		if (x.length < 5 || x.length > 9 || !checkText(x)) {
    			canGo = false;
    			setTimeout("$('#trID').show()",tout);
    		}
    		else {
    			setTimeout("$('#trID').hide()",tout);
    		}
    	}
    }
    function checkLastDigits(x) {
    	if (x.length < 4 || x.length > 6) {
    		canGo = false;
    		setTimeout("$('#trLastDigitsReq').show()",tout);
    	}
    	else {
    		if (!checkText(x))
    			setTimeout("$('#trLastDigitsReq').show()",tout);
    		else
    			setTimeout("$('#trLastDigitsReq').hide()",tout);
    	}
    }
    function checkPassword(x) {
    	if (x.length < 1) {
    		canGo = false;
    		setTimeout("$('#trPasswordReq').show()",tout);
    		setTimeout("$('#trPassword').hide()",tout);
    	}
    	else {
    		setTimeout("$('#trPasswordReq').hide()",tout);
    		if (document.getElementById('trPassword')) {
    			if (!checkPasswordRegExp(x)) {
    				canGo = false;
    				setTimeout("$('#trPassword').show()",tout);
    			}
    			else {
    				setTimeout("$('#trPassword').hide()",tout);
    			}
    		}
    	}
    }
    function checkQuestion(x) {
    	if (x.length < 1) {
    		canGo = false;
    		setTimeout("$('#trQuestionReq').show()",tout);
    	}
    	else {
    		setTimeout("$('#trQuestionReq').hide()",tout);
    	}
    }
    function checkAnswer(x) {
    	if (x.length < 1) {
    		canGo = false;
    		setTimeout("$('#trAnswerReq').show()",tout);
    		setTimeout("$('#trAnswerWrong').hide()",tout);
    	}
    	else {
    		setTimeout("$('#trAnswerReq').hide()",tout);
    		if (!checkText(x))
    			setTimeout("$('#trAnswerWrong').show()",tout);
    		else
    			setTimeout("$('#trAnswerWrong').hide()",tout);
    	}
    }
    function checkCard(x) {
    	if (x.length < 1) {
    		canGo = false;
    		setTimeout("$('#trCardReq').show()",tout);
    	}
    	else {
    		if (!checkText(x))
    			setTimeout("$('#trCardReq').show()",tout);
    		else
    			setTimeout("$('#trCardReq').hide()",tout);
    	}
    }
    function checkCardType(x) {
    	if (x.length < 1) {
    		canGo = false;
    		setTimeout("$('#trCardTypeReq').show()",tout);
    	}
    	else {
    		setTimeout("$('#trCardTypeReq').hide()", tout);
    	}
    }

// Copyright (C) 2005-2008 Ilya S. Lyubinskiy. All rights reserved.
// Technical support: http://www.php-development.ru/
//
// YOU MAY NOT
// (1) Remove or modify this copyright notice.
// (2) Re-distribute this code or any part of it.
//     Instead, you may link to the homepage of this code:
//     http://www.php-development.ru/javascripts/dropdown.php
//
// YOU MAY
// (1) Use this code on your website.
// (2) Use this code as part of another product.
//
// NO WARRANTY
// This code is provided "as is" without warranty of any kind.
// You expressly acknowledge and agree that use of this code is at your own risk.


// ***** Popup Control *********************************************************

// ***** at_show_aux *****
// Red SubMenu




function menuIn() {
    var att = $(this).attr("id").replace("child_", "");     
    $("li.anchorclass[rel='" + att + "']").css('background', '#ffffff');
    $("li.anchorclass[rel='" + att + "']").css('color', '#c90000');
    $("li.anchorclass[rel='" + att + "']").find("a").addClass("menutitleOn").removeClass("menutitle");

    //$("li.anchorclass[rel='" + att + "']").attr("style", "color: #c90000 !important; background:#ffffff; "); 
}


function menuOut() {
    var att = $(this).attr("id").replace("child_", "");
    $("li.anchorclass[rel='" + att + "']").find("a").addClass("menutitle").removeClass("menutitleOn");
    $("li.anchorclass[rel='" + att + "']").css('background', '#c90000');
    $("li.anchorclass[rel='" + att + "']").css('color', '#ffffff');
}

$(document).ready(function(){

    $("div.sample_attach").hoverIntent({

        sensitivity: 7,   // number = sensitivity threshold (must be 1 or higher)
        interval: 0,    // number = milliseconds of polling interval
        over: menuIn,   // function = onMouseOver callback (required)
        timeout: 0,       // number = milliseconds delay before onMouseOut function call
        out: menuOut    // function = onMouseOut callback (required)

    });

  
//    $("div.subMenu ul li").mouseover(function () {
//        $(this).addClass('redBg');
//        $("div.subMenu ul li a").addClass('redBgLink');
//    });

//    $("div.subMenu ul li").mouseout(function () {
//        $(this).removeClass('redBg');
    //    });

    $("div.subMenu ul li").hoverIntent(function () {
        $(this).addClass('redBg');
        $("div.subMenu ul li a").addClass('redBgLink');
    },

    function () {
        $(this).removeClass('redBg');
    });

});


function at_show_aux(p, c) {

  var islast = $(p).attr("islast")
  var left = 0;
  //var top = 114; //  (c["at_position"] == "x") ? p.offsetHeight + 2 : 0;
  //var top = document.getElementById("generalMenuList").offsetTop + 23;   //offsetTop gives 10px less in IE7
  var top = $("#generalMenuList").offset().top + 23;


  var lWidth = p.offsetWidth;
  var cWidth = c.offsetWidth;


  //  top += p.offsetTop;

  for (; p; p = p.offsetParent) {
      if ('right' == 'right') {
          left += p.offsetLeft;
      }
      else {
          left += p.offsetLeft;
      }
  }


  if ('right' == 'right') {
      left -= cWidth;
      left += lWidth + 8;
      c.style.left = left + 'px';

  }
  else {
      //left -= 10;

      left -= (window.navigator.userAgent.indexOf("MSIE 7.0") > -1 ? 10 : 8);

      c.style.left = left + 'px';
  }

  //top += 18;

  if (islast == "1") {
      if ('right' == 'right') {

          left += cWidth;
          //left -= lWidth + 10;
                    
          left -= lWidth + (window.navigator.userAgent.indexOf("MSIE 7.0")>-1? 10 : 9);

          c.style.left = left + 'px';
      }
      else {

          left -= cWidth;
          //left += lWidth + 10;

          left += lWidth + (window.navigator.userAgent.indexOf("MSIE 7.0") > -1 ? 10 : 9);

          c.style.left = left + 'px';
      }
  }

  c.style.position   = "absolute";
  c.style.top        = top +'px';

  c.style.visibility = "visible";
}

// ***** at_show *****

function at_show()
{
  var p = document.getElementById(this["at_parent"]);
  var c = document.getElementById(this["at_child"]);

  

  at_show_aux(p, c);
  clearTimeout(c["at_timeout"]);
}

// ***** at_hide *****

function at_hide()
{
  var p = document.getElementById(this["at_parent"]);
  var c = document.getElementById(this["at_child" ]);

  c["at_timeout"] = setTimeout("document.getElementById('"+c.id+"').style.visibility = 'hidden'", 100);
}

// ***** at_click *****

function at_click()
{
  var p = document.getElementById(this["at_parent"]);
  var c = document.getElementById(this["at_child" ]);

  if (c.style.visibility != "visible") at_show_aux(p.id, c.id); else c.style.visibility = "hidden";
  return false;
}

// ***** at_attach *****

// PARAMETERS:
// parent   - id of the parent html element
// child    - id of the child  html element that should be droped down
// showtype - "click" = drop down child html element on mouse click
//            "hover" = drop down child html element on mouse over
// position - "x" = display the child html element to the right
//            "y" = display the child html element below
// cursor   - omit to use default cursor or specify CSS cursor name

function at_attach(parent, child, showtype, position, cursor) {
    

  var p = document.getElementById(parent);
  var c = document.getElementById(child);

  p["at_parent"]     = p.id;
  c["at_parent"]     = p.id;
  p["at_child"]      = c.id;
  c["at_child"]      = c.id;
  p["at_position"]   = position;
  c["at_position"]   = position;

  c.style.position   = "absolute";
  c.style.visibility = "hidden";

  if (cursor != undefined) p.style.cursor = cursor;

  switch (showtype)
  {
    case "click":
      p.onclick     = at_click;
      p.onmouseout  = at_hide;
      c.onmouseover = at_show;
      c.onmouseout  = at_hide;
      break;
    case "hover":
      p.onmouseover = at_show;
      p.onmouseout  = at_hide;
      c.onmouseover = at_show;
      c.onmouseout  = at_hide;
      break;
  }
}

jQuery.fn.extend({captify:function(a){var a=$.extend({speedOver:"fast",speedOut:"normal",hideDelay:500,animation:"slide",prefix:"",opacity:"0.35",className:"caption-bottom",position:"bottom",spanWidth:"100%"},a);$(this).each(function(){var b=this;$(this).load(function(){$this=b;if(this.hasInit){return false}this.hasInit=true;var d=false;var m=false;var g=$("#"+$(this).attr("rel"));var f=!g.length?$(this).attr("alt"):g.html();g.remove();var h=this.parent&&this.parent.tagName=="a"?this.parent:$(this);var c=h.wrapper("<div></div>").parent();c.css({overflow:"hidden",padding:0,fontSize:0.1});c.addClass("caption-wrapper");c.width($(this).width());c.height($(this).height());$.map(["top","right","bottom","left"],function(p){c.css("margin-"+p,$(b).css("margin-"+p));$.map(["style","width","color"],function(q){var r="border-"+p+"-"+q;c.css(r,$(b).css(r))})});$(b).css({border:"0 none"});var o=$("div:last",c.append("<div></div>")).addClass(a.className);var l=$("div:last",c.append("<div></div>")).addClass(a.className).append(a.prefix).append(f);$("*",c).css({margin:0}).show();var j=jQuery.browser.msie?"static":"relative";o.css({zIndex:1,position:j,opacity:a.animation=="fade"?0:a.opacity,width:a.spanWidth});if(a.position=="bottom"){var k=parseInt(o.css("border-top-width").replace("px",""))+parseInt(l.css("padding-top").replace("px",""))-1;l.css("paddingTop",k)}l.css({position:j,zIndex:2,background:"none",border:"0 none",opacity:a.animation=="fade"?0:1,width:a.spanWidth});o.width(l.outerWidth());o.height(l.height());var n=(a.position=="bottom"&&jQuery.browser.msie)?-4:0;var i=(a.position=="top")?{hide:-$(b).height()-o.outerHeight()-1,show:-$(b).height()}:{hide:0,show:-o.outerHeight()+n};l.css("marginTop",-o.outerHeight());o.css("marginTop",i[a.animation=="fade"||a.animation=="always-on"?"show":"hide"]);var e=function(){if(!d&&!m){var p=a.animation=="fade"?{opacity:0}:{marginTop:i.hide};o.animate(p,a.speedOut);if(a.animation=="fade"){l.animate({opacity:0},a.speedOver)}}};if(a.animation!="always-on"){$(this).hover(function(){m=true;if(!d){var p=a.animation=="fade"?{opacity:a.opacity}:{marginTop:i.show};o.animate(p,a.speedOver);if(a.animation=="fade"){l.animate({opacity:1},a.speedOver/2)}}},function(){m=false;window.setTimeout(e,a.hideDelay)});$("div",c).hover(function(){d=true},function(){d=false;window.setTimeout(e,a.hideDelay)})}});if(this.complete||this.naturalWidth>0){$(b).trigger("load")}})}});
/*
 * SimpleModal 1.3.5 - jQuery Plugin
 * http://www.ericmmartin.com/projects/simplemodal/
 * Copyright (c) 2010 Eric Martin (http://twitter.com/EricMMartin)
 * Dual licensed under the MIT and GPL licenses
 * Revision: $Id: jquery.simplemodal.js 245 2010-03-25 20:41:15Z emartin24 $
 */

/**
 * SimpleModal is a lightweight jQuery plugin that provides a simple
 * interface to create a modal dialog.
 *
 * The goal of SimpleModal is to provide developers with a cross-browser 
 * overlay and container that will be populated with data provided to
 * SimpleModal.
 *
 * There are two ways to call SimpleModal:
 * 1) As a chained function on a jQuery object, like $('#myDiv').modal();.
 * This call would place the DOM object, #myDiv, inside a modal dialog.
 * Chaining requires a jQuery object. An optional options object can be
 * passed as a parameter.
 *
 * @example $('<div>my data</div>').modal({options});
 * @example $('#myDiv').modal({options});
 * @example jQueryObject.modal({options});
 *
 * 2) As a stand-alone function, like $.modal(data). The data parameter
 * is required and an optional options object can be passed as a second
 * parameter. This method provides more flexibility in the types of data 
 * that are allowed. The data could be a DOM object, a jQuery object, HTML
 * or a string.
 * 
 * @example $.modal('<div>my data</div>', {options});
 * @example $.modal('my data', {options});
 * @example $.modal($('#myDiv'), {options});
 * @example $.modal(jQueryObject, {options});
 * @example $.modal(document.getElementById('myDiv'), {options}); 
 * 
 * A SimpleModal call can contain multiple elements, but only one modal 
 * dialog can be created at a time. Which means that all of the matched
 * elements will be displayed within the modal container.
 * 
 * SimpleModal internally sets the CSS needed to display the modal dialog
 * properly in all browsers, yet provides the developer with the flexibility
 * to easily control the look and feel. The styling for SimpleModal can be 
 * done through external stylesheets, or through SimpleModal, using the
 * overlayCss and/or containerCss options.
 *
 * SimpleModal has been tested in the following browsers:
 * - IE 6, 7, 8
 * - Firefox 2, 3
 * - Opera 9, 10
 * - Safari 3, 4
 * - Chrome 1, 2, 3, 4
 *
 * @name SimpleModal
 * @type jQuery
 * @requires jQuery v1.2.2
 * @cat Plugins/Windows and Overlays
 * @author Eric Martin (http://ericmmartin.com)
 * @version 1.3.5
 */
;(function ($) {
	var ie6 = $.browser.msie && parseInt($.browser.version) == 6 && typeof window['XMLHttpRequest'] != "object",
		ieQuirks = null,
		w = [];

	/*
	 * Stand-alone function to create a modal dialog.
	 * 
	 * @param {string, object} data A string, jQuery object or DOM object
	 * @param {object} [options] An optional object containing options overrides
	 */
	$.modal = function (data, options) {
		return $.modal.impl.init(data, options);
	};

	/*
	 * Stand-alone close function to close the modal dialog
	 */
	$.modal.close = function () {
		$.modal.impl.close();
	};

	/*
	 * Chained function to create a modal dialog.
	 * 
	 * @param {object} [options] An optional object containing options overrides
	 */
	$.fn.modal = function (options) {
		return $.modal.impl.init(this, options);
	};

	/*
	 * SimpleModal default options
	 * 
	 * appendTo:		(String:'body') The jQuery selector to append the elements to. For ASP.NET, use 'form'.
	 * focus:			(Boolean:true) Forces focus to remain on the modal dialog
	 * opacity:			(Number:50) The opacity value for the overlay div, from 0 - 100
	 * overlayId:		(String:'simplemodal-overlay') The DOM element id for the overlay div
	 * overlayCss:		(Object:{}) The CSS styling for the overlay div
	 * containerId:		(String:'simplemodal-container') The DOM element id for the container div
	 * containerCss:	(Object:{}) The CSS styling for the container div
	 * dataId:			(String:'simplemodal-data') The DOM element id for the data div
	 * dataCss:			(Object:{}) The CSS styling for the data div
	 * minHeight:		(Number:null) The minimum height for the container
	 * minWidth:		(Number:null) The minimum width for the container
	 * maxHeight:		(Number:null) The maximum height for the container. If not specified, the window height is used.
	 * maxWidth:		(Number:null) The maximum width for the container. If not specified, the window width is used.
	 * autoResize:		(Boolean:false) Resize container on window resize? Use with caution - this may have undesirable side-effects.
	 * autoPosition:	(Boolean:true) Automatically position container on creation and window resize?
	 * zIndex:			(Number: 1000) Starting z-index value
	 * close:			(Boolean:true) If true, closeHTML, escClose and overClose will be used if set.
	 							If false, none of them will be used.
	 * closeHTML:		(String:'<a class="modalCloseImg" title="Close"></a>') The HTML for the 
							default close link. SimpleModal will automatically add the closeClass to this element.
	 * closeClass:		(String:'simplemodal-close') The CSS class used to bind to the close event
	 * escClose:		(Boolean:true) Allow Esc keypress to close the dialog? 
	 * overlayClose:	(Boolean:false) Allow click on overlay to close the dialog?
	 * position:		(Array:null) Position of container [top, left]. Can be number of pixels or percentage
	 * persist:			(Boolean:false) Persist the data across modal calls? Only used for existing
								DOM elements. If true, the data will be maintained across modal calls, if false,
								the data will be reverted to its original state.
	 * modal:			(Boolean:true) If false, the overlay, iframe, and certain events will be disabled
								allowing the user to interace with the page below the dialog
	 * onOpen:			(Function:null) The callback function used in place of SimpleModal's open
	 * onShow:			(Function:null) The callback function used after the modal dialog has opened
	 * onClose:			(Function:null) The callback function used in place of SimpleModal's close
	 */
	$.modal.defaults = {
		appendTo: 'body',
		focus: true,
		opacity: 50,
		overlayId: 'simplemodal-overlay',
		overlayCss: {},
		containerId: 'simplemodal-container',
		containerCss: {},
		dataId: 'simplemodal-data',
		dataCss: {},
		minHeight: null,
		minWidth: null,
		maxHeight: null,
		maxWidth: null,
		autoResize: false,
		autoPosition: true,
		zIndex: 1000,
		close: true,
		closeHTML: '<a class="modalCloseImg" title="Close"></a>',
		closeClass: 'simplemodal-close',
		escClose: true,
		overlayClose: false,
		position: null,
		persist: false,
		modal: true,
		onOpen: null,
		onShow: null,
		onClose: null
	};

	/*
	 * Main modal object
	 */
	$.modal.impl = {
		/*
		 * Modal dialog options
		 */
		o: null,
		/*
		 * Contains the modal dialog elements and is the object passed 
		 * back to the callback (onOpen, onShow, onClose) functions
		 */
		d: {},
		/*
		 * Initialize the modal dialog
		 */
		init: function (data, options) {
			var s = this;

			// don't allow multiple calls
			if (s.d.data) {
				return false;
			}

			// $.boxModel is undefined if checked earlier
			ieQuirks = $.browser.msie && !$.boxModel;

			// merge defaults and user options
			s.o = $.extend({}, $.modal.defaults, options);

			// keep track of z-index
			s.zIndex = s.o.zIndex;

			// set the onClose callback flag
			s.occb = false;

			// determine how to handle the data based on its type
			if (typeof data == 'object') {
				// convert DOM object to a jQuery object
				data = data instanceof jQuery ? data : $(data);
				s.d.placeholder = false;

				// if the object came from the DOM, keep track of its parent
				if (data.parent().parent().size() > 0) {
					data.before($('<span></span>')
						.attr('id', 'simplemodal-placeholder')
						.css({display: 'none'}));

					s.d.placeholder = true;
					s.display = data.css('display');

					// persist changes? if not, make a clone of the element
					if (!s.o.persist) {
						s.d.orig = data.clone(true);
					}
				}
			}
			else if (typeof data == 'string' || typeof data == 'number') {
				// just insert the data as innerHTML
				data = $('<div></div>').html(data);
			}
			else {
				// unsupported data type!
				alert('SimpleModal Error: Unsupported data type: ' + typeof data);
				return s;
			}

			// create the modal overlay, container and, if necessary, iframe
			s.create(data);
			data = null;

			// display the modal dialog
			s.open();

			// useful for adding events/manipulating data in the modal dialog
			if ($.isFunction(s.o.onShow)) {
				s.o.onShow.apply(s, [s.d]);
			}

			// don't break the chain =)
			return s;
		},
		/*
		 * Create and add the modal overlay and container to the page
		 */
		create: function (data) {
			var s = this;

			// get the window properties
			w = s.getDimensions();

			// add an iframe to prevent select options from bleeding through
			if (s.o.modal && ie6) {
				s.d.iframe = $('<iframe src="javascript:false;"></iframe>')
					.css($.extend(s.o.iframeCss, {
						display: 'none',
						opacity: 0, 
						position: 'fixed',
						height: w[0],
						width: w[1],
						zIndex: s.o.zIndex,
						top: 0,
						left: 0
					}))
					.appendTo(s.o.appendTo);
			}

			// create the overlay
			s.d.overlay = $('<div></div>')
				.attr('id', s.o.overlayId)
				.addClass('simplemodal-overlay')
				.css($.extend(s.o.overlayCss, {
					display: 'none',
					opacity: s.o.opacity / 100,
					height: s.o.modal ? w[0] : 0,
					width: s.o.modal ? w[1] : 0,
					position: 'fixed',
					left: 0,
					top: 0,
					zIndex: s.o.zIndex + 1
				}))
				.appendTo(s.o.appendTo);
		
			// create the container
			s.d.container = $('<div></div>')
				.attr('id', s.o.containerId)
				.addClass('simplemodal-container')
				.css($.extend(s.o.containerCss, {
					display: 'none',
					position: 'fixed', 
					zIndex: s.o.zIndex + 2
				}))
				.append(s.o.close && s.o.closeHTML
					? $(s.o.closeHTML).addClass(s.o.closeClass)
					: '')
				.appendTo(s.o.appendTo);
				
			s.d.wrap = $('<div></div>')
				.attr('tabIndex', -1)
				.addClass('simplemodal-wrap')
				.css({height: '100%', outline: 0, width: '100%'})
				.appendTo(s.d.container);
				
			// add styling and attributes to the data
			// append to body to get correct dimensions, then move to wrap
			s.d.data = data
				.attr('id', data.attr('id') || s.o.dataId)
				.addClass('simplemodal-data')
				.css($.extend(s.o.dataCss, {
						display: 'none'
				}))
				.appendTo('body');
			data = null;

			s.setContainerDimensions();
			s.d.data.appendTo(s.d.wrap);

			// fix issues with IE
			if (ie6 || ieQuirks) {
				s.fixIE();
			}
		},
		/*
		 * Bind events
		 */
		bindEvents: function () {
			var s = this;

			// bind the close event to any element with the closeClass class
			$('.' + s.o.closeClass).bind('click.simplemodal', function (e) {
				e.preventDefault();
				s.close();
			});
			
			// bind the overlay click to the close function, if enabled
			if (s.o.modal && s.o.close && s.o.overlayClose) {
				s.d.overlay.bind('click.simplemodal', function (e) {
					e.preventDefault();
					s.close();
				});
			}
	
			// bind keydown events
			$(document).bind('keydown.simplemodal', function (e) {
				if (s.o.modal && s.o.focus && e.keyCode == 9) { // TAB
					s.watchTab(e);
				}
				else if ((s.o.close && s.o.escClose) && e.keyCode == 27) { // ESC
					e.preventDefault();
					s.close();
				}
			});

			// update window size
			$(window).bind('resize.simplemodal', function () {
				// redetermine the window width/height
				w = s.getDimensions();

				// reposition the dialog
				s.setContainerDimensions(true);
	
				if (ie6 || ieQuirks) {
					s.fixIE();
				}
				else if (s.o.modal) {
					// update the iframe & overlay
					s.d.iframe && s.d.iframe.css({height: w[0], width: w[1]});
					s.d.overlay.css({height: w[0], width: w[1]});
				}
			});
		},
		/*
		 * Unbind events
		 */
		unbindEvents: function () {
			$('.' + this.o.closeClass).unbind('click.simplemodal');
			$(document).unbind('keydown.simplemodal');
			$(window).unbind('resize.simplemodal');
			this.d.overlay.unbind('click.simplemodal');
		},
		/*
		 * Fix issues in IE6 and IE7 in quirks mode
		 */
		fixIE: function () {
			var s = this, p = s.o.position;

			// simulate fixed position - adapted from BlockUI
			$.each([s.d.iframe || null, !s.o.modal ? null : s.d.overlay, s.d.container], function (i, el) {
				if (el) {
					var bch = 'document.body.clientHeight', bcw = 'document.body.clientWidth',
						bsh = 'document.body.scrollHeight', bsl = 'document.body.scrollLeft',
						bst = 'document.body.scrollTop', bsw = 'document.body.scrollWidth',
						ch = 'document.documentElement.clientHeight', cw = 'document.documentElement.clientWidth',
						sl = 'document.documentElement.scrollLeft', st = 'document.documentElement.scrollTop',
						s = el[0].style;

					s.position = 'absolute';
					if (i < 2) {
						s.removeExpression('height');
						s.removeExpression('width');
						s.setExpression('height','' + bsh + ' > ' + bch + ' ? ' + bsh + ' : ' + bch + ' + "px"');
						s.setExpression('width','' + bsw + ' > ' + bcw + ' ? ' + bsw + ' : ' + bcw + ' + "px"');
					}
					else {
						var te, le;
						if (p && p.constructor == Array) {
							var top = p[0] 
								? typeof p[0] == 'number' ? p[0].toString() : p[0].replace(/px/, '')
								: el.css('top').replace(/px/, '');
							te = top.indexOf('%') == -1 
								? top + ' + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"'
								: parseInt(top.replace(/%/, '')) + ' * ((' + ch + ' || ' + bch + ') / 100) + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"';

							if (p[1]) {
								var left = typeof p[1] == 'number' ? p[1].toString() : p[1].replace(/px/, '');
								le = left.indexOf('%') == -1 
									? left + ' + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"'
									: parseInt(left.replace(/%/, '')) + ' * ((' + cw + ' || ' + bcw + ') / 100) + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"';
							}
						}
						else {
							te = '(' + ch + ' || ' + bch + ') / 2 - (this.offsetHeight / 2) + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"';
							le = '(' + cw + ' || ' + bcw + ') / 2 - (this.offsetWidth / 2) + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"';
						}
						s.removeExpression('top');
						s.removeExpression('left');
						s.setExpression('top', te);
						s.setExpression('left', le);
					}
				}
			});
		},
		focus: function (pos) {
			var s = this, p = pos || 'first';

			// focus on dialog or the first visible/enabled input element
			var input = $(':input:enabled:visible:' + p, s.d.wrap);
			input.length > 0 ? input.focus() : s.d.wrap.focus();
		},
		getDimensions: function () {
			var el = $(window);

			// fix a jQuery/Opera bug with determining the window height
			var h = $.browser.opera && $.browser.version > '9.5' && $.fn.jquery <= '1.2.6' ? document.documentElement['clientHeight'] :
				$.browser.opera && $.browser.version < '9.5' && $.fn.jquery > '1.2.6' ? window.innerHeight :
				el.height();

			return [h, el.width()];
		},
		getVal: function (v) {
			return v == 'auto' ? 0 
				: v.indexOf('%') > 0 ? v 
					: parseInt(v.replace(/px/, ''));
		},
		setContainerDimensions: function (resize) {
			var s = this;

			if (!resize || (resize && s.o.autoResize)) {
				// get the dimensions for the container and data
				var ch = $.browser.opera ? s.d.container.height() : s.getVal(s.d.container.css('height')), 
					cw = $.browser.opera ? s.d.container.width() : s.getVal(s.d.container.css('width')),
					dh = s.d.data.outerHeight(true), dw = s.d.data.outerWidth(true);

				var mh = s.o.maxHeight && s.o.maxHeight < w[0] ? s.o.maxHeight : w[0],
					mw = s.o.maxWidth && s.o.maxWidth < w[1] ? s.o.maxWidth : w[1];

				// height
				if (!ch) {
					if (!dh) {ch = s.o.minHeight;}
					else {
						if (dh > mh) {ch = mh;}
						else if (dh < s.o.minHeight) {ch = s.o.minHeight;}
						else {ch = dh;}
					}
				}
				else {
					ch = ch > mh ? mh : ch;
				}

				// width
				if (!cw) {
					if (!dw) {cw = s.o.minWidth;}
					else {
						if (dw > mw) {cw = mw;}
						else if (dw < s.o.minWidth) {cw = s.o.minWidth;}
						else {cw = dw;}
					}
				}
				else {
					cw = cw > mw ? mw : cw;
				}

				s.d.container.css({height: ch, width: cw});
				if (dh > ch || dw > cw) {
					s.d.wrap.css({overflow:'auto'});
				}
			}
			
			if (s.o.autoPosition) {
				s.setPosition();
			}
		},
		setPosition: function () {
			var s = this, top, left,
				hc = (w[0]/2) - (s.d.container.outerHeight(true)/2),
				vc = (w[1]/2) - (s.d.container.outerWidth(true)/2);

			if (s.o.position && Object.prototype.toString.call(s.o.position) === "[object Array]") {
				top = s.o.position[0] || hc;
				left = s.o.position[1] || vc;
			} else {
				top = hc;
				left = vc;
			}
			s.d.container.css({left: left, top: top});
		},
		watchTab: function (e) {
			var s = this;

			if ($(e.target).parents('.simplemodal-container').length > 0) {
				// save the list of inputs
				s.inputs = $(':input:enabled:visible:first, :input:enabled:visible:last', s.d.data[0]);

				// if it's the first or last tabbable element, refocus
				if ((!e.shiftKey && e.target == s.inputs[s.inputs.length -1]) ||
						(e.shiftKey && e.target == s.inputs[0]) ||
						s.inputs.length == 0) {
					e.preventDefault();
					var pos = e.shiftKey ? 'last' : 'first';
					setTimeout(function () {s.focus(pos);}, 10);
				}
			}
			else {
				// might be necessary when custom onShow callback is used
				e.preventDefault();
				setTimeout(function () {s.focus();}, 10);
			}
		},
		/*
		 * Open the modal dialog elements
		 * - Note: If you use the onOpen callback, you must "show" the 
		 *	        overlay and container elements manually 
		 *         (the iframe will be handled by SimpleModal)
		 */
		open: function () {
			var s = this;
			// display the iframe
			s.d.iframe && s.d.iframe.show();

			if ($.isFunction(s.o.onOpen)) {
				// execute the onOpen callback 
				s.o.onOpen.apply(s, [s.d]);
			}
			else {
				// display the remaining elements
				s.d.overlay.show();
				s.d.container.show();
				s.d.data.show();
			}
			
			s.focus();

			// bind default events
			s.bindEvents();
		},
		/*
		 * Close the modal dialog
		 * - Note: If you use an onClose callback, you must remove the 
		 *         overlay, container and iframe elements manually
		 *
		 * @param {boolean} external Indicates whether the call to this
		 *     function was internal or external. If it was external, the
		 *     onClose callback will be ignored
		 */
		close: function () {
			var s = this;

			// prevent close when dialog does not exist
			if (!s.d.data) {
				return false;
			}

			// remove the default events
			s.unbindEvents();

			if ($.isFunction(s.o.onClose) && !s.occb) {
				// set the onClose callback flag
				s.occb = true;

				// execute the onClose callback
				s.o.onClose.apply(s, [s.d]);
			}
			else {
				// if the data came from the DOM, put it back
				if (s.d.placeholder) {
					var ph = $('#simplemodal-placeholder');
					// save changes to the data?
					if (s.o.persist) {
						// insert the (possibly) modified data back into the DOM
						ph.replaceWith(s.d.data.removeClass('simplemodal-data').css('display', s.display));
					}
					else {
						// remove the current and insert the original, 
						// unmodified data back into the DOM
						s.d.data.hide().remove();
						ph.replaceWith(s.d.orig);
					}
				}
				else {
					// otherwise, remove it
					s.d.data.hide().remove();
				}

				// remove the remaining elements
				s.d.container.hide().remove();
				s.d.overlay.hide().remove();
				s.d.iframe && s.d.iframe.hide().remove();

				// reset the dialog object
				s.d = {};
			}
		}
	};
})(jQuery);

var prev = -1;
var current = -1;

/**
 * jCarouselLite - jQuery plugin to navigate images/any content in a carousel style widget.
 * @requires jQuery v1.2 or above
 *
 * http://gmarwaha.com/jquery/jcarousellite/
 * 
 * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Version: 1.0.1
 * Note: Requires jquery 1.2 or above from version 1.0.1
 */

/**
 * Creates a carousel-style navigation widget for images/any-content from a simple HTML markup.
 *
 * The HTML markup that is used to build the carousel can be as simple as...
 *
 *  <div class="carousel">
 *      <ul>
 *          <li><img src="image/1.jpg" alt="1"></li>
 *          <li><img src="image/2.jpg" alt="2"></li>
 *          <li><img src="image/3.jpg" alt="3"></li>
 *      </ul>
 *  </div>
 *
 * As you can see, this snippet is nothing but a simple div containing an unordered list of images.
 * You don't need any special "class" attribute, or a special "css" file for this plugin.
 * I am using a class attribute just for the sake of explanation here.
 *
 * To navigate the elements of the carousel, you need some kind of navigation buttons.
 * For example, you will need a "previous" button to go backward, and a "next" button to go forward.
 * This need not be part of the carousel "div" itself. It can be any element in your page.
 * Lets assume that the following elements in your document can be used as next, and prev buttons...
 *
 * <button class="prev">&lt;&lt;</button>
 * <button class="next">&gt;&gt;</button>
 *
 * Now, all you need to do is call the carousel component on the div element that represents it, and pass in the
 * navigation buttons as options.
 *
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev"
 * });
 *
 * That's it, you would have now converted your raw div, into a magnificient carousel.
 *
 * There are quite a few other options that you can use to customize it though.
 * Each will be explained with an example below.
 *
 * @param an options object - You can specify all the options shown below as an options object param.
 *
 * @option btnPrev, btnNext : string - no defaults
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev"
 * });
 * @desc Creates a basic carousel. Clicking "btnPrev" navigates backwards and "btnNext" navigates forward.
 *
 * @option btnGo - array - no defaults
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      btnGo: [".0", ".1", ".2"]
 * });
 * @desc If you don't want next and previous buttons for navigation, instead you prefer custom navigation based on
 * the item number within the carousel, you can use this option. Just supply an array of selectors for each element
 * in the carousel. The index of the array represents the index of the element. What i mean is, if the
 * first element in the array is ".0", it means that when the element represented by ".0" is clicked, the carousel
 * will slide to the first element and so on and so forth. This feature is very powerful. For example, i made a tabbed
 * interface out of it by making my navigation elements styled like tabs in css. As the carousel is capable of holding
 * any content, not just images, you can have a very simple tabbed navigation in minutes without using any other plugin.
 * The best part is that, the tab will "slide" based on the provided effect. :-)
 *
 * @option mouseWheel : boolean - default is false
 * @example
 * $(".carousel").jCarouselLite({
 *      mouseWheel: true
 * });
 * @desc The carousel can also be navigated using the mouse wheel interface of a scroll mouse instead of using buttons.
 * To get this feature working, you have to do 2 things. First, you have to include the mouse-wheel plugin from brandon.
 * Second, you will have to set the option "mouseWheel" to true. That's it, now you will be able to navigate your carousel
 * using the mouse wheel. Using buttons and mouseWheel or not mutually exclusive. You can still have buttons for navigation
 * as well. They complement each other. To use both together, just supply the options required for both as shown below.
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      mouseWheel: true
 * });
 *
 * @option auto : number - default is null, meaning autoscroll is disabled by default
 * @example
 * $(".carousel").jCarouselLite({
 *      auto: 800,
 *      speed: 500
 * });
 * @desc You can make your carousel auto-navigate itself by specfying a millisecond value in this option.
 * The value you specify is the amount of time between 2 slides. The default is null, and that disables auto scrolling.
 * Specify this value and magically your carousel will start auto scrolling.
 *
 * @option speed : number - 200 is default
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      speed: 800
 * });
 * @desc Specifying a speed will slow-down or speed-up the sliding speed of your carousel. Try it out with
 * different speeds like 800, 600, 1500 etc. Providing 0, will remove the slide effect.
 *
 * @option easing : string - no easing effects by default.
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      easing: "bounceout"
 * });
 * @desc You can specify any easing effect. Note: You need easing plugin for that. Once specified,
 * the carousel will slide based on the provided easing effect.
 *
 * @option vertical : boolean - default is false
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      vertical: true
 * });
 * @desc Determines the direction of the carousel. true, means the carousel will display vertically. The next and
 * prev buttons will slide the items vertically as well. The default is false, which means that the carousel will
 * display horizontally. The next and prev items will slide the items from right-right in this case.
 *
 * @option circular : boolean - default is true
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      circular: false
 * });
 * @desc Setting it to true enables circular navigation. This means, if you click "next" after you reach the last
 * element, you will automatically slide to the first element and vice versa. If you set circular to false, then
 * if you click on the "next" button after you reach the last element, you will stay in the last element itself
 * and similarly for "previous" button and first element.
 *
 * @option visible : number - default is 3
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      visible: 4
 * });
 * @desc This specifies the number of items visible at all times within the carousel. The default is 3.
 * You are even free to experiment with real numbers. Eg: "3.5" will have 3 items fully visible and the
 * last item half visible. This gives you the effect of showing the user that there are more images to the right.
 *
 * @option start : number - default is 0
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      start: 2
 * });
 * @desc You can specify from which item the carousel should start. Remember, the first item in the carousel
 * has a start of 0, and so on.
 *
 * @option scrool : number - default is 1
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      scroll: 2
 * });
 * @desc The number of items that should scroll/slide when you click the next/prev navigation buttons. By
 * default, only one item is scrolled, but you may set it to any number. Eg: setting it to "2" will scroll
 * 2 items when you click the next or previous buttons.
 *
 * @option beforeStart, afterEnd : function - callbacks
 * @example
 * $(".carousel").jCarouselLite({
 *      btnNext: ".next",
 *      btnPrev: ".prev",
 *      beforeStart: function(a) {
 *          alert("Before animation starts:" + a);
 *      },
 *      afterEnd: function(a) {
 *          alert("After animation ends:" + a);
 *      }
 * });
 * @desc If you wanted to do some logic in your page before the slide starts and after the slide ends, you can
 * register these 2 callbacks. The functions will be passed an argument that represents an array of elements that
 * are visible at the time of callback.
 *
 *
 * @cat Plugins/Image Gallery
 * @author Ganeshji Marwaha/ganeshread@gmail.com
 */

(function($) {                                          // Compliant with jquery.noConflict()
    $.fn.jCarouselLite = function(o) {
        o = $.extend({
            btnPrev: null,
            btnNext: null,
            btnGo: null,
            mouseWheel: false,
            auto: null,

            speed: 200,
            easing: null,

            vertical: false,
            circular: false,
            visible: 3,
            start: 0,
            scroll: 1,
            totalItemInCarousel: 5,

            //            background: null,
            //            backgroundCurrent: null,


            beforeStart: null,
            afterEnd: null
        }, o || {});

        return this.each(function() {                           // Returns the element collection. Chainable.

            var running = false, animCss = o.vertical ? "top" : "right", sizeCss = o.vertical ? "height" : "width";
            var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;

            if (o.circular) {
                ul.prepend(tLi.slice(tl - v - 1 + 1).clone())
              .append(tLi.slice(0, v).clone());
                o.start += v;
            }

            var li = $("li", ul), itemLength = li.size(), curr = o.start;
            div.css("visibility", "visible");

            li.css({ overflow: "hidden", float: o.vertical ? "none" : "right" });
            ul.css({ margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1" });
            div.css({ overflow: "hidden", position: "relative", "z-index": "2", right: "0px" });

            var liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
            var ulSize = liSize * itemLength;                   // size of full ul(total length, not just for the visible items)
            var divSize = liSize * v;                           // size of entire div(total length for just the visible items)

            li.css({ width: li.width(), height: li.height() });
            ul.css(sizeCss, ulSize + "px").css(animCss, -(curr * liSize));

            div.css(sizeCss, divSize + "px");                     // Width of the DIV. length of visible images
            
            if (o.btnPrev)
                $(o.btnPrev).click(function() {


                   // if (current == -1) {
                   //     current = o.start + 1;
                   // }

                    prev = current;

                    current = current - 1;


                    //  if (current == 0)
                    //      current = 1;
                    
                    $(".prev").css("opacity", "1");
                    if (current <= 0) {
                        $(".next").css("opacity", "0.3");
                    }
                    else
                        $(".next").css("opacity", "1");




                    //                    alert(current)
                    //$('.carousel' + prev).css("opacity", "0.3");
                    //                    $('.carousel' + current).css("opacity", "1");

                    /*        //   if (current == o.totalItemInCarousel) {
                    if (current == 1) {
                    $(".next").css("opacity", "0.3");
                    }
                    else
                    $(".next").css("opacity", "1");

                    $(".prev").css("opacity", "1");
                    */


                    //        $('#details' + prev).hide();
                    //          $('#details' + current).show();


                    return go(curr - o.scroll);

                });


            if (o.btnNext)
                $(o.btnNext).click(function() {


                   // if (current == -1) {
                   //     current = o.start + 1;
                   // }

                    prev = current;

                    if ((current-1) + o.visible >= o.totalItemInCarousel)
                        current = current;
                    else
                        current = current + 1;
                    //alert(current)


                    if (current + o.visible >= o.totalItemInCarousel) {
                        $(".prev").css("opacity", "0.3");
                    }
                    else
                        $(".prev").css("opacity", "1");

                    $(".next").css("opacity", "1");

                    /*
                    //        $('.carousel' + prev).css("opacity", "0.3");
                    //                    $('.carousel' + current).css("opacity", "1");
                    var x = Number(o.visible) - Number(current) - 1;
 

                   
                    if (current == x) {
                    $(".prev").css("opacity", "0.3");
                    }
                    else
                    $(".prev").css("opacity", "1");

                    $(".next").css("opacity", "1"); 
                    */
                    //if (current = 7)
                    //  $(".next").css("opacity", "0.3"); 

                    //                    $('#details' + prev).hide();
                    //                    $('#details' + current).show();
                    //alert(current)
                    return go(curr + o.scroll);
                });

            if (o.btnGo)
                $.each(o.btnGo, function(i, val) {
                    $(val).click(function() {
                        return go(o.circular ? o.visible + i : i);
                    });
                });

            if (o.mouseWheel && div.mousewheel)
                div.mousewheel(function(e, d) {
                    return d > 0 ? go(curr - o.scroll) : go(curr + o.scroll);
                });

            if (o.auto)
                setInterval(function() {
                    go(curr + o.scroll);
                }, o.auto + o.speed);

            function vis() {
                
                return li.slice(curr).slice(0, v);
            };

            function go(to) {

                if (!running) {

                    if (o.beforeStart)
                        o.beforeStart.call(this, vis());

                    if (o.circular) {            // If circular we are in first or last, then goto the other end
                        if (to <= o.start - v - 1) {           // If first, then goto last
                            ul.css(animCss, -((itemLength - (v * 2)) * liSize) + "px");
                            // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
                            curr = to == o.start - v - 1 ? itemLength - (v * 2) - 1 : itemLength - (v * 2) - o.scroll;
                        } else if (to >= itemLength - v + 1) { // If last, then goto first
                            ul.css(animCss, -((v) * liSize) + "px");
                            // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
                            curr = to == itemLength - v + 1 ? v + 1 : v + o.scroll;
                        } else curr = to;
                    } else {                    // If non-circular and to points to first or last, we just return.
                        if (to < 0 || to > itemLength - v) return;
                        else curr = to;
                    }                           // If neither overrides it, the curr will still be "to" and we can proceed.

                    running = true;

                     if ('right' == 'right') {
                          ul.animate(
                                animCss == "right" ? { right: -(curr * liSize)} : { top: -(curr * liSize) }, o.speed, o.easing,
                                function() {
                                    if (o.afterEnd)
                                        o.afterEnd.call(this, vis());
                                    running = false;
                                }
                            );
                      }
                      else {
                          ul.animate(
                                animCss == "right" ? { right: +(curr * liSize)} : { top: -(curr * liSize) }, o.speed, o.easing,
                                function() {
                                    if (o.afterEnd)
                                        o.afterEnd.call(this, vis());
                                    running = false;
                                }
                            );
                      }


                    
                    // Disable buttons when the carousel reaches the last/first, and enable when not
                    if (!o.circular) {
                        $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
                        $((curr - o.scroll < 0 && o.btnPrev)
                        ||
                       (curr + o.scroll > itemLength - v && o.btnNext)
                        ||
                       []
                     ).addClass("disabled");
                    }

                }
                return false;
            };
        });
    };

    function css(el, prop) {
        return parseInt($.css(el[0], prop)) || 0;
    };
    function width(el) {
        return el[0].offsetWidth + css(el, 'marginright') + css(el, 'marginRight');
    };
    function height(el) {
        return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
    };

})(jQuery);

(function($){$.fn.filestyle=function(options){var settings={width:250};if(options){$.extend(settings,options);};return this.each(function(){var self=this;var wrapper=$("<div>").css({"width":settings.imagewidth+"px","height":settings.imageheight+"px","background":"url("+settings.image+") 0 0 no-repeat","background-position":"right","display":"inline","position":"absolute","overflow":"hidden"});var filename=$('<input class="file">').addClass($(self).attr("class")).css({"display":"inline","width":settings.width+"px"});$(self).before(filename);$(self).wrap(wrapper);$(self).css({"position":"relative","height":settings.imageheight+"px","width":settings.width+"px","display":"inline","cursor":"pointer","opacity":"0.0"});if($.browser.mozilla){if(/Win/.test(navigator.platform)){$(self).css("margin-left","-142px");}else{$(self).css("margin-left","-168px");};}else{$(self).css("margin-left",settings.imagewidth-settings.width+"px");};$(self).bind("change",function(){filename.val($(self).val());});});};})(jQuery);
/*
* Autocomplete - jQuery plugin 1.1pre
*
* Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.autocomplete.js 5785 2008-07-12 10:37:33Z joern.zaefferer $
*
*/


; (function ($) {

    $.fn.extend({
        autocomplete: function (urlOrData, options) {
            var isUrl = typeof urlOrData == "string";
            options = $.extend({}, $.Autocompleter.defaults, {
                url: isUrl ? urlOrData : null,
                data: isUrl ? null : urlOrData,
                delay: isUrl ? $.Autocompleter.defaults.delay : 10,
                max: options && !options.scroll ? 10 : 150
            }, options);

            // if highlight is set to false, replace it with a do-nothing function
            options.highlight = options.highlight || function (value) { return value; };

            // if the formatMatch option is not specified, then use formatItem for backwards compatibility
            options.formatMatch = options.formatMatch || options.formatItem;

            return this.each(function () {
                new $.Autocompleter(this, options);
            });
        },
        result: function (handler) {
            return this.bind("result", handler);
        },
        search: function (handler) {
            return this.trigger("search", [handler]);
        },
        flushCache: function () {
            return this.trigger("flushCache");
        },
        setOptions: function (options) {
            return this.trigger("setOptions", [options]);
        },
        unautocomplete: function () {
            return this.trigger("unautocomplete");
        }
    });

    $.Autocompleter = function (input, options) {

        var KEY = {
            UP: 38,
            DOWN: 40,
            DEL: 46,
            TAB: 9,
            RETURN: 13,
            ESC: 27,
            COMMA: 188,
            PAGEUP: 33,
            PAGEDOWN: 34,
            BACKSPACE: 8
        };

        // Create $ object for input element
        var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

        var timeout;
        var previousValue = "";
        var cache = $.Autocompleter.Cache(options);
        var hasFocus = 0;
        var lastKeyPressCode;
        var config = {
            mouseDownOnSelect: false
        };
        var select = $.Autocompleter.Select(options, input, selectCurrent, config);

        var blockSubmit;

        // prevent form submit in opera when selecting with return key
        $.browser.opera && $(input.form).bind("submit.autocomplete", function () {
            if (blockSubmit) {
                blockSubmit = false;
                return false;
            }
        });

        // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
        $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function (event) {
            // track last key pressed
            lastKeyPressCode = event.keyCode;
            switch (event.keyCode) {

                case KEY.UP:
                    event.preventDefault();
                    if (select.visible()) {
                        select.prev();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.DOWN:
                    event.preventDefault();
                    if (select.visible()) {
                        select.next();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEUP:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageUp();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEDOWN:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageDown();
                    } else {
                        onChange(0, true);
                    }
                    break;

                // matches also semicolon 
                case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
                case KEY.TAB:
                case KEY.RETURN:
                    if (selectCurrent()) {
                        // stop default to prevent a form submit, Opera needs special handling
                        event.preventDefault();
                        blockSubmit = true;
                        return false;
                    }
                    break;

                case KEY.ESC:
                    select.hide();
                    break;

                default:
                    clearTimeout(timeout);
                    timeout = setTimeout(onChange, options.delay);
                    break;
            }
        }).focus(function () {
            // track whether the field has focus, we shouldn't process any
            // results if the field no longer has focus
            hasFocus++;
        }).blur(function () {
            hasFocus = 0;
            if (!config.mouseDownOnSelect) {
                hideResults();
            }
        }).click(function () {
            // show select when clicking in a focused field
            if (hasFocus++ > 1 && !select.visible()) {
                onChange(0, true);
            }
        }).bind("search", function () {
            // TODO why not just specifying both arguments?
            var fn = (arguments.length > 1) ? arguments[1] : null;
            function findValueCallback(q, data) {
                var result;
                if (data && data.length) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].result.toLowerCase() == q.toLowerCase()) {
                            result = data[i];
                            break;
                        }
                    }
                }
                if (typeof fn == "function") fn(result);
                else $input.trigger("result", result && [result.data, result.value]);
            }
            $.each(trimWords($input.val()), function (i, value) {
                request(value, findValueCallback, findValueCallback);
            });
        }).bind("flushCache", function () {
            cache.flush();
        }).bind("setOptions", function () {
            $.extend(options, arguments[1]);
            // if we've updated the data, repopulate
            if ("data" in arguments[1])
                cache.populate();
        }).bind("unautocomplete", function () {
            select.unbind();
            $input.unbind();
            $(input.form).unbind(".autocomplete");
        });


        function selectCurrent() {
            var selected = select.selected();
            if (!selected)
                return false;

            var v = selected.result;
            previousValue = v;

            if (options.multiple) {
                var words = trimWords($input.val());
                if (words.length > 1) {
                    v = words.slice(0, words.length - 1).join(options.multipleSeparator) + options.multipleSeparator + v;
                }
                v += options.multipleSeparator;
            }

            $input.val(v);
            hideResultsNow();
            $input.trigger("result", [selected.data, selected.value]);
            return true;
        }

        function onChange(crap, skipPrevCheck) {
            if (lastKeyPressCode == KEY.DEL) {
                select.hide();
                return;
            }

            var currentValue = $input.val();

            if (!skipPrevCheck && currentValue == previousValue)
                return;

            previousValue = currentValue;

            currentValue = lastWord(currentValue);
            if (currentValue.length >= options.minChars) {
                $input.addClass(options.loadingClass);
                if (!options.matchCase)
                    currentValue = currentValue.toLowerCase();
                request(currentValue, receiveData, hideResultsNow);
            } else {
                stopLoading();
                select.hide();
            }
        };

        function trimWords(value) {
            if (!value) {
                return [""];
            }
            var words = value.split(options.multipleSeparator);
            var result = [];
            $.each(words, function (i, value) {
                if ($.trim(value))
                    result[i] = $.trim(value);
            });
            return result;
        }

        function lastWord(value) {
            if (!options.multiple)
                return value;
            var words = trimWords(value);
            return words[words.length - 1];
        }

        // fills in the input box w/the first match (assumed to be the best match)
        // q: the term entered
        // sValue: the first matching result
        function autoFill(q, sValue) {
            // autofill in the complete box w/the first match as long as the user hasn't entered in more data
            // if the last user key pressed was backspace, don't autofill
            if (options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE) {
                // fill in the value (keep the case the user has typed)
                $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
                // select the portion of the value not typed by the user (so the next character will erase)
                $.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
            }
        };

        function hideResults() {
            clearTimeout(timeout);
            timeout = setTimeout(hideResultsNow, 200);
        };

        function hideResultsNow() {
            var wasVisible = select.visible();
            select.hide();
            clearTimeout(timeout);
            stopLoading();
            if (options.mustMatch) {
                // call search and run callback
                $input.search(
				function (result) {
				    // if no value found, clear the input box
				    if (!result) {
				        if (options.multiple) {
				            var words = trimWords($input.val()).slice(0, -1);
				            $input.val(words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : ""));
				        }
				        else
				            $input.val("");
				    }
				}
			);
            }
            if (wasVisible)
            // position cursor at end of input field
                $.Autocompleter.Selection(input, input.value.length, input.value.length);
        };

        function receiveData(q, data) {
            if (data && data.length && hasFocus) {
                stopLoading();
                select.display(data, q);
                autoFill(q, data[0].value);
                select.show();
            } else {
                hideResultsNow();
            }
        };

        function request(term, success, failure) {
            if (!options.matchCase)
                term = term.toLowerCase();
            var data = cache.load(term);
            // recieve the cached data
            if (data && data.length) {
                success(term, data);
                // if an AJAX url has been supplied, try loading the data now
            } else if ((typeof options.url == "string") && (options.url.length > 0)) {

                var extraParams = {
                    timestamp: +new Date()
                };
                $.each(options.extraParams, function (key, param) {
                    extraParams[key] = typeof param == "function" ? param() : param;
                });

                $.ajax({
                    // try to leverage ajaxQueue plugin to abort previous requests
                    mode: "abort",
                    // limit abortion to this input
                    port: "autocomplete" + input.name,
                    dataType: options.dataType,
                    url: options.url,
                    data: $.extend({
                        q: lastWord(term),
                        limit: options.max
                    }, extraParams),
                    success: function (data) {
                        var parsed = options.parse && options.parse(data) || parse(data);
                        cache.add(term, parsed);
                        success(term, parsed);
                    }
                });
            } else {
                // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
                select.emptyList();
                failure(term);
            }
        };

        function parse(data) {
            var parsed = [];
            var rows = data.split("\n");
            for (var i = 0; i < rows.length; i++) {
                var row = $.trim(rows[i]);
                if (row) {
                    row = row.split("|");
                    parsed[parsed.length] = {
                        data: row,
                        value: row[0],
                        result: options.formatResult && options.formatResult(row, row[0]) || row[0]
                    };
                }
            }
            return parsed;
        };

        function stopLoading() {
            $input.removeClass(options.loadingClass);
        };

    };

    $.Autocompleter.defaults = {
        inputClass: "ac_input",
        resultsClass: "ac_results",
        loadingClass: "ac_loading",
        minChars: 1,
        delay: 400,
        matchCase: false,
        matchSubset: true,
        matchContains: false,
        cacheLength: 10,
        max: 100,
        mustMatch: false,
        extraParams: {},
        selectFirst: true,
        formatItem: function (row) { return row[0]; },
        formatMatch: null,
        autoFill: false,
        width: 0,
        multiple: false,
        multipleSeparator: ", ",
        highlight: function (value, term) {
            return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
        },
        scroll: true,
        scrollHeight: 180
    };

    $.Autocompleter.Cache = function (options) {

        var data = {};
        var length = 0;

        function matchSubset(s, sub) {
            if (!options.matchCase)
                s = s.toLowerCase();
            var i = s.indexOf(sub);
            if (options.matchContains == "word") {
                i = s.toLowerCase().search("\\b" + sub.toLowerCase());
            }
            if (i == -1) return false;
            return i == 0 || options.matchContains;
        };

        function add(q, value) {
            if (length > options.cacheLength) {
                flush();
            }
            if (!data[q]) {
                length++;
            }
            data[q] = value;
        }

        function populate() {
            if (!options.data) return false;
            // track the matches
            var stMatchSets = {},
			nullData = 0;

            // no url was specified, we need to adjust the cache length to make sure it fits the local data store
            if (!options.url) options.cacheLength = 1;

            // track all options for minChars = 0
            stMatchSets[""] = [];

            // loop through the array and create a lookup structure
            for (var i = 0, ol = options.data.length; i < ol; i++) {
                var rawValue = options.data[i];
                // if rawValue is a string, make an array otherwise just reference the array
                rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;

                var value = options.formatMatch(rawValue, i + 1, options.data.length);
                if (value === false)
                    continue;

                var firstChar = value.charAt(0).toLowerCase();
                // if no lookup array for this character exists, look it up now
                if (!stMatchSets[firstChar])
                    stMatchSets[firstChar] = [];

                // if the match is a string
                var row = {
                    value: value,
                    data: rawValue,
                    result: options.formatResult && options.formatResult(rawValue) || value
                };

                // push the current match into the set list
                stMatchSets[firstChar].push(row);

                // keep track of minChars zero items
                if (nullData++ < options.max) {
                    stMatchSets[""].push(row);
                }
            };

            // add the data items to the cache
            $.each(stMatchSets, function (i, value) {
                // increase the cache size
                options.cacheLength++;
                // add to the cache
                add(i, value);
            });
        }

        // populate any existing data
        setTimeout(populate, 25);

        function flush() {
            data = {};
            length = 0;
        }

        return {
            flush: flush,
            add: add,
            populate: populate,
            load: function (q) {
                if (!options.cacheLength || !length)
                    return null;
                /* 
                * if dealing w/local data and matchContains than we must make sure
                * to loop through all the data collections looking for matches
                */
                if (!options.url && options.matchContains) {
                    // track all matches
                    var csub = [];
                    // loop through all the data grids for matches
                    for (var k in data) {
                        // don't search through the stMatchSets[""] (minChars: 0) cache
                        // this prevents duplicates
                        if (k.length > 0) {
                            var c = data[k];
                            $.each(c, function (i, x) {
                                // if we've got a match, add it to the array
                                if (matchSubset(x.value, q)) {
                                    csub.push(x);
                                }
                            });
                        }
                    }
                    return csub;
                } else
                // if the exact item exists, use it
                    if (data[q]) {
                        return data[q];
                    } else
                        if (options.matchSubset) {
                            for (var i = q.length - 1; i >= options.minChars; i--) {
                                var c = data[q.substr(0, i)];
                                if (c) {
                                    var csub = [];
                                    $.each(c, function (i, x) {
                                        if (matchSubset(x.value, q)) {
                                            csub[csub.length] = x;
                                        }
                                    });
                                    return csub;
                                }
                            }
                        }
                return null;
            }
        };
    };

    $.Autocompleter.Select = function (options, input, select, config) {
        var CLASSES = {
            ACTIVE: "ac_over"
        };

        var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list;

        // Create results
        function init() {
            if (!needsInit)
                return;
            element = $("<div/>")
		.hide()
		.addClass(options.resultsClass)
		.css("position", "absolute")
		.appendTo(document.body);

            list = $("<ul/>").appendTo(element).mouseover(function (event) {
                if (target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
                    active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
                    $(target(event)).addClass(CLASSES.ACTIVE);
                }
            }).click(function (event) {
                $(target(event)).addClass(CLASSES.ACTIVE);
                select();
                // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
                input.focus();
                return false;
            }).mousedown(function () {
                config.mouseDownOnSelect = true;
            }).mouseup(function () {
                config.mouseDownOnSelect = false;
            });

            if (options.width > 0)
                element.css("width", options.width);

            needsInit = false;
        }

        function target(event) {
            var element = event.target;
            while (element && element.tagName != "LI")
                element = element.parentNode;
            // more fun with IE, sometimes event.target is empty, just ignore it then
            if (!element)
                return [];
            return element;
        }

        function moveSelect(step) {
            listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
            movePosition(step);
            var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
            if (options.scroll) {
                var offset = 0;
                listItems.slice(0, active).each(function () {
                    offset += this.offsetHeight;
                });
                if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                    list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
                } else if (offset < list.scrollTop()) {
                    list.scrollTop(offset);
                }
            }
        };

        function movePosition(step) {
            active += step;
            if (active < 0) {
                active = listItems.size() - 1;
            } else if (active >= listItems.size()) {
                active = 0;
            }
        }

        function limitNumberOfItems(available) {
            return options.max && options.max < available
			? options.max
			: available;
        }

        function fillList() {
            list.empty();
            var max = limitNumberOfItems(data.length);
            for (var i = 0; i < max; i++) {
                if (!data[i])
                    continue;
                var formatted = options.formatItem(data[i].data, i + 1, max, data[i].value, term);
                if (formatted === false)
                    continue;
                var li = $("<li/>").html(options.highlight(formatted, term)).addClass(i % 2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
                $.data(li, "ac_data", data[i]);
            }
            listItems = list.find("li");
            if (options.selectFirst) {
                listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
                active = 0;
            }
            // apply bgiframe if available
            if ($.fn.bgiframe)
                list.bgiframe();
        }

        return {
            display: function (d, q) {
                init();
                data = d;
                term = q;
                fillList();
            },
            next: function () {
                moveSelect(1);
            },
            prev: function () {
                moveSelect(-1);
            },
            pageUp: function () {
                if (active != 0 && active - 8 < 0) {
                    moveSelect(-active);
                } else {
                    moveSelect(-8);
                }
            },
            pageDown: function () {
                if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
                    moveSelect(listItems.size() - 1 - active);
                } else {
                    moveSelect(8);
                }
            },
            hide: function () {
                element && element.hide();
                listItems && listItems.removeClass(CLASSES.ACTIVE);
                active = -1;
            },
            visible: function () {
                return element && element.is(":visible");
            },
            current: function () {
                return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
            },
            show: function () {
                var offset = $(input).offset();
                element.css({
                    width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
                    top: offset.top + input.offsetHeight,
                    left: offset.left
                }).show();
                if (options.scroll) {
                    list.scrollTop(0);
                    list.css({
                        maxHeight: options.scrollHeight,
                        overflow: 'auto'
                    });

                    if ($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
                        var listHeight = 0;
                        listItems.each(function () {
                            listHeight += this.offsetHeight;
                        });
                        var scrollbarsVisible = listHeight > options.scrollHeight;
                        list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight);
                        if (!scrollbarsVisible) {
                            // IE doesn't recalculate width when scrollbar disappears
                            listItems.width(list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")));
                        }
                    }

                }
            },
            selected: function () {
                var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
                return selected && selected.length && $.data(selected[0], "ac_data");
            },
            emptyList: function () {
                list && list.empty();
            },
            unbind: function () {
                element && element.remove();
            }
        };
    };

    $.Autocompleter.Selection = function (field, start, end) {
        if (field.createTextRange) {
            var selRange = field.createTextRange();
            selRange.collapse(true);
            selRange.moveStart("character", start);
            selRange.moveEnd("character", end);
            selRange.select();
        } else if (field.setSelectionRange) {
            field.setSelectionRange(start, end);
        } else {
            if (field.selectionStart) {
                field.selectionStart = start;
                field.selectionEnd = end;
            }
        }
        field.focus();
    };

})(jQuery);





 

