
function doCufon(){
	/* cufon */
    Cufon.replace('#nav li a.first, .mega .top', {
        fontFamily: 'Berthold Akzidenz Grotesk BE',
        textShadow: '1px 1px rgba(0, 1px, 1px, 1)',
        hover: true
    });
    Cufon.replace('.mega h2', {
        fontFamily: 'Berthold Akzidenz Grotesk BE',
        textShadow: '1px 2px rgba(0,0,0)',
        hover: true
    });
    Cufon.replace('.togglers li', {
        fontFamily: 'Berthold Akzidenz Grotesk BE',
        textShadow: '1px 1px rgba(0, 1px, 1px, 1)',
        hover: true
    });
    Cufon.replace('.module h5', {
        fontFamily: 'Berthold Akzidenz Grotesk BE',
        hover: true
    });
    Cufon.replace('.module .ribbon', {
        fontFamily: 'Berthold Akzidenz Grotesk BE',
        hover: true
    });
    Cufon.replace('#search_go', {
        fontFamily: 'Berthold Akzidenz Grotesk BE'
    });

    Cufon.replace('.coverage .stock, .coverage .company, #price_targets .header', {
        fontFamily: 'Berthold Akzidenz Grotesk BE',
        textShadow: '1px 1px rgba(0, 1px, 1px, 1)'
    });
	
	if (!$('#content.home').length) {
		Cufon.replace('h1', {
			fontFamily: 'Berthold Akzidenz Grotesk BE',
			textShadow: '1px 1px rgba(0, 1px, 1px, 1)'
		});
	}
	
    Cufon.replace('.body .hdr, .content_top .module .header, .coverage_list .header', {
        fontFamily: 'Berthold Akzidenz Grotesk BE',
    textShadow: '1px 1px rgba(0, 1px, 1px, 1)'
    });
    Cufon.replace('.box h3, .box h4', {
        fontFamily: 'Berthold Akzidenz Grotesk BE',
		textShadow: '1px 1px rgba(0, 1px, 1px, 1)'
    });
    Cufon.replace('.interior h1:not(.alt), .tab h2, .listing h2, .tab h3, .tab .story h4, .testimonial h5, #subnav li, .interior .total', {
        fontFamily: 'Berthold Akzidenz Grotesk BE',
        hover: true
    });
    Cufon.replace('.interior h1.alt span, h1.alt em', {
        fontFamily: 'Berthold Akzidenz Grotesk BE',
        hover: true
    });
    Cufon.replace('.hero .text p, .hero .cta, .interior #column_a .nav li', {
        fontFamily: 'Berthold Akzidenz Grotesk BE',
		textShadow: '1px 1px rgba(0, 1px, 1px, 1)',
		hover: true
    });
    Cufon.replace('.home .bottom h2, #nav_utility .hdr', {
        fontFamily: 'Berthold Akzidenz Grotesk BE',
		hover: true
    });
    Cufon.now();
}

//doCufon();

var ie6 = $.browser.msie && $.browser.version == "6.0";
/*--------------------------------------------------------------------------*/

/**
 * hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
 * <http://cherne.net/brian/resources/jquery.hoverIntent.html>
 *
 * @param  f  onMouseOver function || An object with configuration options
 * @param  g  onMouseOut function  || Nothing (use configuration options object)
 * @author    Brian Cherne <brian@cherne.net>
 */
(function($){
    $.fn.hoverIntent = function(f, g){
        var cfg = {
            sensitivity: 7,
            interval: 100,
            timeout: 0
        };
        cfg = $.extend(cfg, g ? {
            over: f,
            out: g
        } : f);
        var cX, cY, pX, pY;
        var track = function(ev){
            cX = ev.pageX;
            cY = ev.pageY;
        };
        var compare = function(ev, ob){
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            if ((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) {
                $(ob).unbind("mousemove", track);
                ob.hoverIntent_s = 1;
                return cfg.over.apply(ob, [ev]);
            }
            else {
                pX = cX;
                pY = cY;
                ob.hoverIntent_t = setTimeout(function(){
                    compare(ev, ob);
                }, cfg.interval);
            }
        };
        var delay = function(ev, ob){
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            ob.hoverIntent_s = 0;
            return cfg.out.apply(ob, [ev]);
        };
        var handleHover = function(e){
            var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
            while (p && p != this) {
                try {
                    p = p.parentNode;
                } 
                catch (e) {
                    p = this;
                }
            }
            if (p == this) {
                return false;
            }
            var ev = jQuery.extend({}, e);
            var ob = this;
            if (ob.hoverIntent_t) {
                ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            }
            if (e.type == "mouseover") {
                pX = ev.pageX;
                pY = ev.pageY;
                $(ob).bind("mousemove", track);
                if (ob.hoverIntent_s != 1) {
                    ob.hoverIntent_t = setTimeout(function(){
                        compare(ev, ob);
                    }, cfg.interval);
                }
            }
            else {
                $(ob).unbind("mousemove", track);
                if (ob.hoverIntent_s == 1) {
                    ob.hoverIntent_t = setTimeout(function(){
                        delay(ev, ob);
                    }, cfg.timeout);
                }
            }
        };
        return this.mouseover(handleHover).mouseout(handleHover);
    };
})(jQuery);



/*--------------------------------------------------------------------------*/

// jQuery SWFObject v1.1.1 MIT/GPL @jon_neal
// http://jquery.thewikies.com/swfobject
(function(f, h, i){
    function k(a, c){
        var b = (a[0] || 0) - (c[0] || 0);
        return b > 0 || !b && a.length > 0 && k(a.slice(1), c.slice(1))
    }
    function l(a){
        if (typeof a != g) 
            return a;
        var c = [], b = "";
        for (var d in a) {
            b = typeof a[d] == g ? l(a[d]) : [d, m ? encodeURI(a[d]) : a[d]].join("=");
            c.push(b)
        }
        return c.join("&")
    }
    function n(a){
        var c = [];
        for (var b in a) 
            a[b] && c.push([b, '="', a[b], '"'].join(""));
        return c.join(" ")
    }
    function o(a){
        var c = [];
        for (var b in a) 
            c.push(['<param name="', b, '" value="', l(a[b]), '" />'].join(""));
        return c.join("")
    }
    var g = "object", m = true;
    try {
        var j = i.description || function(){
            return (new i("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version")
        }()
    } 
    catch (p) {
        j = "Unavailable"
    }
    var e = j.match(/\d+/g) || [0];
    f[h] = {
        available: e[0] > 0,
        activeX: i && !i.name,
        version: {
            original: j,
            array: e,
            string: e.join("."),
            major: parseInt(e[0], 10) || 0,
            minor: parseInt(e[1], 10) || 0,
            release: parseInt(e[2], 10) || 0
        },
        hasVersion: function(a){
            a = /string|number/.test(typeof a) ? a.toString().split(".") : /object/.test(typeof a) ? [a.major, a.minor] : a || [0, 0];
            return k(e, a)
        },
        encodeParams: true,
        expressInstall: "expressInstall.swf",
        expressInstallIsActive: false,
        create: function(a){
            if (!a.swf || this.expressInstallIsActive || !this.available && !a.hasVersionFail) 
                return false;
            if (!this.hasVersion(a.hasVersion || 1)) {
                this.expressInstallIsActive = true;
                if (typeof a.hasVersionFail == "function") 
                    if (!a.hasVersionFail.apply(a)) 
                        return false;
                a = {
                    swf: a.expressInstall || this.expressInstall,
                    height: 137,
                    width: 214,
                    flashvars: {
                        MMredirectURL: location.href,
                        MMplayerType: this.activeX ? "ActiveX" : "PlugIn",
                        MMdoctitle: document.title.slice(0, 47) + " - Flash Player Installation"
                    }
                }
            }
            attrs = {
                data: a.swf,
                type: "application/x-shockwave-flash",
                id: a.id || "flash_" + Math.floor(Math.random() * 999999999),
                width: a.width || 320,
                height: a.height || 180,
                style: a.style || ""
            };
            m = typeof a.useEncode !== "undefined" ? a.useEncode : this.encodeParams;
            a.movie = a.swf;
            a.wmode = a.wmode || "opaque";
            delete a.fallback;
            delete a.hasVersion;
            delete a.hasVersionFail;
            delete a.height;
            delete a.id;
            delete a.swf;
            delete a.useEncode;
            delete a.width;
            var c = document.createElement("div");
            c.innerHTML = ["<object ", n(attrs), ">", o(a), "</object>"].join("");
            return c.firstChild
        }
    };
    f.fn[h] = function(a){
        var c = this.find(g).andSelf().filter(g);
        /string|object/.test(typeof a) && this.each(function(){
            var b = f(this), d;
            a = typeof a == g ? a : {
                swf: a
            };
            a.fallback = this;
            if (d = f[h].create(a)) {
                b.children().remove();
                b.html(d)
            }
        });
        typeof a == "function" && c.each(function(){
            var b = this;
            b.jsInteractionTimeoutMs = b.jsInteractionTimeoutMs || 0;
            if (b.jsInteractionTimeoutMs < 660) 
                b.clientWidth || b.clientHeight ? a.call(b) : setTimeout(function(){
                    f(b)[h](a)
                }, b.jsInteractionTimeoutMs + 66)
        });
        return c
    }
})(jQuery, "flash", navigator.plugins["Shockwave Flash"] || window.ActiveXObject);

/*--------------------------------------------------------------------------*/

jQuery.fn.center = function(){
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    return this;
}

/*--------------------------------------------------------------------------*/

var Tabs = function (togglers, tabs, start, opts) {
	this.togglers = $(togglers);
	this.tabs = $(tabs);
	this.start = start;
	
	this.defaults = {
		showCB: function () {},
		fade: false
	};
	this.options = $.extend({}, this.defaults, opts);
	
	this.setup();
};
Tabs.prototype = {
	setup: function () {
		var self = this;		
		this.show(this.start);
		this.togglers.each(function (i) {
			$(this).click(function (ev) {
				ev.preventDefault();
				self.show(i);
			});
		});
	},
	show: function (idx) {
		this.togglers.removeClass('active');
		$(this.togglers[idx]).addClass('active');
				
		if (this.options.fade) { 
			this.tabs.fadeOut(); 
			$(this.tabs[idx]).fadeIn();
		}
		else { 
			this.tabs.hide(); 
			$(this.tabs[idx]).show();
		}
		
		this.options.showCB();
	}
};

/*--------------------------------------------------------------------------*/

var PopUp = function(trigger, pop, opts){
    this.trigger = $(trigger);
    this.pop = $(pop);
    
    this.defaults = {
        centered: false,
        modal: false,
        modalOverlay: $('#modal_overlay'),
        loader: pop.find('.loader'),
        close: pop.find('.close_overlay'),
        fadeDuration: $.browser.msie ? 0 : 0,
        ajax: false
    };
    this.options = $.extend({}, this.defaults, opts);
    this.setup();
};
PopUp.prototype = {
    setup: function(){
        var self = this;
        this.cache = {};
        
        this.trigger.click(function(ev){
            ev.preventDefault();
            self.open();
        });
    },
    open: function(){
        var self = this;
        
        if (this.options.centered) {
            this.pop.center();
        }
        if (this.options.modal) {
            this.initModalOverlay();
        }
        
        if (this.options.ajax) {
            var url = this.trigger.attr('href');
            this.pop.fadeIn(this.options.fadeDuration, function(){
                if (!self.cache[url]) {
                    self.options.loader.show();
                    $.ajax({
                        url: url,
                        dataType: 'html',
                        context: this,
                        success: function(r){
                            self.options.loader.hide();
                            self.cache[url] = r;
                            $(self.pop).find('.content').html(r);
                        }
                    });
                }
                else {
                    $(self.pop).find('.content').html(self.cache[url]);
                }
            });
        }
        else {
            this.pop.fadeIn(this.options.fadeDuration);
        }
        
     //   this.options.close.click(function(){
     //       self.close();
     //   });
        
     //   $(document).unbind('click');
     //   $(document).bind('closePop', function(){
     //       self.close();
     //   });
     //   this.pop.hover(function(){
     //       $(document).unbind('click');
     //   });
     //   this.pop.bind('mouseleave', function(){
     //       $(document).click(function(){
     //           $(document).trigger('closePop');
     //       });
     //   });
        $("#search_overlay").dropShadow({
            top: 0,
            left: 0,
            blur: 8,
            opacity: 0.7
            }); 
    },
    close: function(){
        this.pop.fadeOut(this.options.fadeDuration);
        this.options.modalOverlay.fadeOut(this.options.fadeDuration);
    },
    initModalOverlay: function(){
        this.options.modalOverlay.css("height", $('body:first').height());
        this.options.modalOverlay.fadeIn(this.options.fadeDuration);
    }
};

/*--------------------------------------------------------------------------*/

var Prompt = function(field){
    this.input = field.find('input');
    this.label = field.find('label');
    this.defaultText = this.label.text();
    this.setup();
};
Prompt.prototype = {
    setup: function(){
        var self = this;
        this.input.val('');
        this.label.click(function(){
            self._focus(true);
        });
        this.input.bind('focus', function(){
            self._focus();
        });
        this.input.bind('blur', function(){
            self._blur();
        });
    },
    _focus: function(focus){
        this.label.hide();
        if (focus) {
            this.input.focus();
        }
        this.input.addClass('active');
    },
    _blur: function(){
        if (this.input.val() == '') {
            this.label.show();
        }
        this.input.removeClass('active');
    }
};

/*--------------------------------------------------------------------------*/

function refreshResults(){
    $.get('/mytag/search', function(data){
        $('.results .listing ol').html(data);
    });
}


function ajaxPost(form){
    $.ajax({
        url: $(form).attr("action"),
        data: $(form).serialize(),
        method: "POST",
        error: function(x, e){
            if (e == 'parsererror') {
                //do nothing
            }
            else {
                showGeneralError();
            }
        },
        dataType: "script"
    });
    return false;
}


function generalError(){
    alert("Error occurred");
}




function update_dependent_radio_buttons(){
      if($("#notify input[type=radio]").attr("checked"))
      {
         $("#research_preferences .dependent input[type=radio]").attr('disabled',false);
      }
      else{
        $("#research_preferences .dependent input[type=radio]").attr('disabled',true);
      }

}

/*--------------------------------------------------------------------------*/

var SlideShow = function (container, slides, delay, initial) {
    this.container = container;
    this.slides = slides;
    this.delay = delay;
    this.current = initial || 0;
    this.togglers = this.container.find('.togglers li');
    this.setup();
};
SlideShow.prototype = {
    setup: function () {
        var self = this;
        this.showOnly($(this.slides[this.current]));
        $(this.togglers[this.current]).addClass('active');
        
        this.togglers.bind('click', function () {
            self.pause();
            self.goTo($(this).index());
        });
		
		this.start();
    },
    showOnly: function (el) {
        this.slides.hide();
        el.show();
    },
    goTo: function (idx) {
        var self = this;
		
        if (idx === this.current) {	return; }
		
        $(this.togglers[this.current]).removeClass('active');
        $(this.slides[this.current]).fadeOut('slow');
        this.current = idx;
		
        $(this.togglers[this.current]).addClass('active');
        $(this.slides[this.current]).fadeIn('slow');
		
        this.start();
    },
    start: function () {
        if (this.timer) { return; }
        var self = this;
        this.timer = setTimeout(function(){
            self.next();
        }, this.delay * 1500);
    },
    pause: function () {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = false;
        }
        else { return; }
    },
    next: function() {
        this.timer = false;
        if (this.current === this.slides.length - 1) { this.goTo(0); }
        else { this.goTo(this.current + 1); }
        this.start();
    }
};

/*--------------------------------------------------------------------------*/
function showResults(search_string){
        $('#companies li').hide();
        $("#companies li").filter('li[rel^="' + search_string.toLowerCase() + '"]').show();
}

function setUpCompanySectorSearch(){
    
    /* search dropdown */
    new PopUp($('#search .trigger'),$('#search .overlay'));
    //$("#search .trigger").fancybox({
    //        autoScale: false,
    //        padding: 0,
    //        autoDimensions: false,
    //        centerOnScroll: true,
    //        scrolling: true,
    //        transitionIn: 'fade'
    //});
    new Tabs($('#search .togglers li'), $('#search .tab'), 0);
    new Prompt($('#search .field'));
	
	$('#nav_utility .field').each(function () { new Prompt($(this)); });

    $('#letters li a').click(function(event){
        event.preventDefault();
        $(this).parent().addClass('active').siblings().removeClass('active');
        var letter = $(this).parent().attr('rel');
        showResults(letter);
    });
    
    $('#company_search').bind('keyup', function(){
        showResults($(this).val());
    });



}

$(document).ready(function(){
    doCufon();
    setUpCompanySectorSearch();

    if (ie6) {
        try {
            document.execCommand('BackgroundImageCache', false, true);
        } 
        catch (e) {
        }
    }
	
	/* megas */
	$('#nav li.trigger').hoverIntent({
		sensitivity: 1,
		interval: 50,
		over: function() { $(this).find('.mega').fadeIn(200); }, 
		out: function() { $(this).find('.mega').fadeOut(200); }		
	});
    
    /* login form  and reset password form */
    if ($('#login').length) {
      new Prompt($('#login #email'));
      new Prompt($('#login #password'));
      if ($('#password_confirm')) {
        new Prompt($('#login #password_confirm'));
      }
    }
	
    $('.preferences .search').each(function () { new Prompt($(this)); });
    
    
    $('#search_field').live({
        keyup: function(){
            if ($('#search_field') && ($('#search_field').val().length > 2)) {
                refreshResults();
            }
        }
    });
    
	/* home */
	if ($('#content.home').length) { new SlideShow($('.hero'), $('.hero .slide'), 15, 0); }
	
    /* landing */
    if ($('#tabs_landing').length) {
        new Tabs($('#tabs_landing .togglers li'), $('#tabs_landing .tab'), 0);
        new Prompt($('.filters .field.text'));
    }
    
    /* filter mytag */
    new Prompt($('.filters .field.text'));
    
    //        $('#search_form').filterform({
    //          url: '/mytag/search',
    //          results_container: '.results'
    //        });
    $("div.results .pagination a").live("click", function(event){
//        $(".pagination").html("Page is loading...");
        // $("div.results div.listing, div.results div.pagination").fadeOut();
        $("div.results  span").addClass("spinning");
    });

    $(".pagination a").live("click", function(event){
        event.preventDefault();
//        $(".pagination").html("Page is loading...");
        // $("div.results div.listing, div.results div.pagination").fadeOut();
        $.getScript(this.href);
        //  $.get(this.href, function(data) {
        //    $('.results').html(data);
        // });
        return false;
    });
    
    
    /* "all" checkbox */
    $("#all input[type=checkbox]").click(function(){
        if ($("#all input:checked").val()) {
            $("#product_types input[type=checkbox]").attr("checked", "checked");
            $("#product_types").hide();
        }
        else {
            $("#product_types input[type=checkbox]").attr("checked", false);
            $("#product_types").show();
        }
    });
    
    $("#all input[type=checkbox], #product_types input[type=checkbox]").attr("checked", "checked");
    
    $("#search_go").click(function(event){
        event.preventDefault();
        $("div.results div.listing, div.results div.pagination").fadeOut();
        $("div.results span").addClass("spinning");
        $("#search_form").submit();
    });
    
    $("#search_form").submit(function(event){
        ids = "";
        $("#product_types input:checked").each(function(index, element){
            ids = ids + element.value + ",";
        });
        $("#product_type_ids").val(ids);
        event.preventDefault();
        ajaxPost("#search_form");
    });

    /* Hint Hiding and such */

    $(".help_quotes input.hint_toggle").click(function(){
      sub_id = $(this).attr("rel");
      value = !$(this).is(':checked');
      $.get("/subscribers/"+sub_id+"/toggle_hint?hint_type=quotes&value="+value);
      $(".help_quotes").fadeOut();
      $(".help_container_quotes .tip_toggle_down").fadeIn();
    });

    $(".help_types input.hint_toggle").click(function(){
      sub_id = $(this).attr("rel");
      value = !$(this).is(':checked');
      $.get("/subscribers/"+sub_id+"/toggle_hint?hint_type=product_types&value="+value);
      $(".help_types").fadeOut();
      $(".help_container_types .tip_toggle_up").fadeIn();
    });

     $(".help_container_types .tip_toggle_up").click(function(){
      $(this).fadeOut();
      checkbox = $(".help_types input.hint_toggle");
      sub_id = checkbox.attr("rel");
      checkbox.attr("checked",false);
      $.get("/subscribers/"+sub_id+"/toggle_hint?hint_type=product_types&value=true");
      $(".help_types").fadeIn();
     });

     $(".help_container_quotes .tip_toggle_down").click(function(){
      $(this).fadeOut();
      checkbox = $(".help_quotes input.hint_toggle");
      sub_id = checkbox.attr("rel");
      checkbox.attr("checked",false);
      $.get("/subscribers/"+sub_id+"/toggle_hint?hint_type=quotes&value=true");
      $(".help_quotes").fadeIn();   
     });


    

    
    /* "sidebar" stuff  -- all messages link */
	if ($('#all_messages').length) {
		$("#all_messages").fancybox({
			width: 600,
			height: 400,
			padding: 0,
			autoDimensions: false,
			centerOnScroll: true,
			scrolling: true,
			transitionIn: 'fade',
			onComplete: function(){ $("#messages").show(); doCufon();},
			onClosed: function(){  $("#messages").hide(); $("#messages").parent().hide();}
		});
	}

    /*RSVP toggles */
    $("#rsvp a").live('click',function(event){
           event.preventDefault();
           link = event.currentTarget;
           $.get($(link).attr("href"));
    });

    /*Sector toggles */
    $("#subscribe button.addto").live('click',function(event){
           event.preventDefault();
           //link = event.currentTarget;
           //alert $(link).attr("rel");
           $.post($(this).attr("rel"));
    });

    $("#subscribe button.removefrom").live('click',function(event){
           event.preventDefault();
           //link = event.currentTarget;
           //alert $(link).attr("rel");
           $.ajax({
              url: $(this).attr("rel"),
              type: "DELETE"
           });
    });

    /*Sector/Company search overlay - cancel/close button*/
    $("a.close_overlay").live('click',function(event){
   link = event.currentTarget;
            event.preventDefault();
           $(link).parent().hide();
           $("#search_overlay").removeShadow();
//            $("#full_page_overlay").hide();
        });
    
    $("a.remote").click(function(event){
        event.preventDefault();
        $.ajax({
              url: $(this).attr("href"),
              dataType: 'script'
            });
        return false;
    });

    /*Sector - show more */
	if ($('.coverage_list').length) {
		$(".coverage_list .more, .coverage_list .header a").fancybox({
			height: 400,
			width: 600,
			padding: 0,
			autoDimensions: false,
			centerOnScroll: true,
			scrolling: 'no',
			transitionIn: 'fade',
			onComplete: function(){ $("#sectors").show(); doCufon();},
			onClosed: function(){  $("#sectors").hide(); $("#sectors").parent().hide();}
		});
	}
    

    $("#research_preferences input[type=radio]").change(function(){
      update_dependent_radio_buttons(); 
    });
    
    update_dependent_radio_buttons(); 

});

