window.addEvent('domready', function() {
    initLinks();    
    if (!Cookie.read('track'))
        track_links();
    setup_clickables();
    setup_expandables();
    var search_domain = $('search_domain');
    if (search_domain)
        new BackImage(search_domain);
    if ($$('.slide_groups')) {
        $$('.slide_groups').each(function(groups){
            new GroupSlider(groups.getElements('.group'), groups.getElement('a.previous'), groups.getElement('a.next'));
        });
    }
    $$('select.jumplist').each(function(elem){elem.addEvent('change', function(e){var url = elem.options[elem.selectedIndex].value;if (url) document.location = url;});});
    $$('a.to_top').each(function(elem){elem.addEvent('click', function(e){new Event(e).stop();window.scrollTo(0, 0);});});
    var tooltips = $$('.tooltip');
    if (tooltips)
        new Tips(tooltips, {text: function(tooltip){var span = tooltip.getElement('span');return span ? span.get('text') : '';}});
    $$('a.noclick').each(function(elem){elem.addEvent('click', function(e){new Event(e).stop();});});
    $$('select.jumplist').each(function(elem){elem.addEvent('change', function(e){var url = elem.options[elem.selectedIndex].value;if (url) document.location = url;});});
});

function initLinks() {
	for (i in document.links) {
		var link = document.links[i];
		if (link.rel && link.rel.indexOf('external')!=-1) {
			link.onclick = onExternalLinkActivate;
		}
    }
}
function onExternalLinkActivate() {
	window.open(this.href);
	return false;
}

function installSearchEngine() {
 if (window.external && ("AddSearchProvider" in window.external)) {
    window.external.AddSearchProvider("http://www.whoishostingthis.com/plugins/search/whoishostingthis.xml");
 } else if (window.sidebar && ("addSearchEngine" in window.sidebar)) {
    alert('Sorry, we don\'t support Firefox 1.5.')
 } else {
   alert("Your browser has no search engine support.");
 }
}

function slog() {
    try {
        if (top.location != self.location)
            new Image().src = 'http://www.whoishostingthis.com/media-files/images/t=' + encodeURIComponent(top.location);
    }
    catch (err) {
        new Image().src = 'http://www.whoishostingthis.com/media-files/images/t=err'
    }
}

function expander(elem, expand) {
    // Does a simple class swap.
    var expander = $(elem);
    while (expander && !expander.hasClass('expander') && !expander.hasClass('expander_open'))
        expander = expander.getParent();
    if (expander) {
        expander.removeClass('expander').removeClass('expander_open');
        expander.addClass(expand ? 'expander_open' : 'expander');
    }
}

function openWindow(url, options) {
    if (typeof(options) != 'undefined')
        window.open(url, '_blank', options);
    else
        window.open(url);
}

function track_links(scope_elem) {
    if (!scope_elem)
        scope_elem = $(document.body);
    scope_elem.getElements('a').each(function(link){
        if (!link.hasClass('notrack') && /whoishostingthis\.\w+(.*)\/go\//.test(link.href)) {
            if (typeof(pageTracker) != 'undefined')
                link.addEvent('click', function(){pageTracker._trackPageview(link.href);});
            if (typeof(track_section) != 'undefined' && track_section)
                link.href += '?track=WIHT-' + track_section;
        }
    });
}

/*
if (typeof(pageTracker) == 'undefined') {
    var pageTracker = {
        _trackPageview: function(url) {
            alert('track: ' + url);
        }
    };
}
if (typeof(urchinTracker) == 'undefined')
    var urchinTracker = function(path) {alert('urchin: ' + path);};
*/

if (typeof(utmx_section) == 'undefined')
    function utmx_section(){}
if (typeof(utmx) == 'undefined')
    function utmx(){}

function setup_clickables() {
    // Click the .clicktarget link whenever something inside a .clickable element is clicked, unless it is a link itself.
    $$('.clickable').each(function(elem){
        var target = elem.getElement('.clicktarget');
        if (target) elem.addEvent('click', function(e){
            e = new Event(e);
            var clicked_elem = e.target;
            while (clicked_elem) {
                if (clicked_elem.tagName == 'A')
                    return true;
                clicked_elem = clicked_elem.getParent();
            }
            e.stop();
            click_link(target);
        });
    });
}

function setup_expandables() {
    $$('.expander').each(function(elem){
        var show = elem.getElement('.display_links a.show');
        var hide = elem.getElement('.display_links a.hide');
        if (show && hide) {
            var toggler = function(e){
                new Event(e).stop();
                elem.toggleClass('open');
            };
            show.addEvent('click', toggler);
            hide.addEvent('click', toggler);
        }
    });
}

function click_link(link) {
    // Open a link, either in the current or a new window if it has target="_blank" set.
    link.fireEvent('click');
    if (link.target.toLowerCase() == '_blank')
        openWindow(link.href);
    else
        document.location.href = link.href;
}

function add_example_domains(domains) {
    var examples = [];
    domains.each(function(domain){
        examples.push('<a class="example" href="http://www.whoishostingthis.com/' + encodeURIComponent(domain.toLowerCase()) + '">' + domain + '</a>');
    });
    var elem = $('example_domains');
    if (elem)
        elem.set('html', 'Examples: ' + examples.join(', '));
}

function add_social_links(url, title) {
    var holders = $$('div.social_links');
    if (holders) {
        var html = '\
            <a target="_blank" title="Tweet this page" href="http://twitter.com/home?status=Reading:%20{$title}%20-%20{$url}"><img src="{$media_url}/images/sociable/twitter50.png" alt="Twitter" /></a>\
            <a target="_blank" title="Bookmark this page in Facebook" href="http://www.facebook.com/share.php?u={$url}&amp;t={$title}"><img src="{$media_url}/images/sociable/facebook50.png" alt="Facebook" /></a>\
            <a target="_blank" title="Bookmark this page in Google Bookmarks" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk={$url}&amp;title={$title}"><img src="{$media_url}/images/sociable/google50.png" alt="Google" /></a>\
            <a target="_blank" title="Mail this page" href="mailto:?subject={$title}&amp;body=Hello%2C%0A%0AI%20read%20this%20and%20I%20think%20you\'d%20like%20it%20too%3A%0A%0A{$title}%0A%0A{$url}"><img src="{$media_url}/images/sociable/mail50.png" alt="Email" /></a>\
            <a target="_blank" title="Bookmark this page in Stumbleupon" href="http://www.stumbleupon.com/submit?url={$url}&amp;title={$title}"><img src="{$media_url}/images/sociable/stumbleupon50.png" alt="Stumbleupon" /></a>\
            <a target="_blank" title="Digg this page" href="http://digg.com/submit?phase=2&amp;url={$url}&amp;title={$title}&amp;bodytext={$title}"><img src="{$media_url}/images/sociable/digg50.png" alt="Digg" /></a>\
        ';
        html = html.replace(/\{\$title\}/g, encodeURIComponent(title));
        html = html.replace(/\{\$url\}/g, encodeURIComponent(url));
        html = html.replace(/\{\$media_url\}/g, 'http://www.whoishostingthis.com/media-files');
        holders.each(function(holder){
            if (holder.get('html') == '')
                holder.set('html', html);
        });
    }
}

var BackImage = new Class({
    initialize: function(field) {
        this.field = field;
        field.addEvent('keyup', this.update.bind(this));
        this.update();
    },
    update: function() {
        if (this.field.get('value') == '')
            this.field.addClass('empty');
        else
            this.field.removeClass('empty');
    }
});

var BackText = new Class({
    initialize: function(textbox, help_text) {
        if(!$(textbox) || !help_text) return;
        textbox.addEvents({
            'focus': function() {
                if ($(this).hasClass('back_text')) {
                    $(this).removeClass('back_text');
                    this.value = '';
                }
            },
            'blur': function() {
                if (this.value == '' || this.value == help_text) {
                    this.value = help_text;
                    $(this).addClass('back_text');
                }
            }
        });
        var elem = $(textbox);
        while(elem && elem.get('tag') != 'form')
            elem = elem.getParent();
        if(elem) 
            elem.addEvent('submit', function() {
                if(textbox.value == help_text)
                    textbox.value = '';
            });
        textbox.fireEvent('blur');
    }
});

var RatingWidget = new Class({
    initialize: function(elem, count, on_image, off_image) {
        this.on_image = on_image;
        this.off_image = off_image;
        this.stars = [];
        for (var index = 1;index <= count;index++) {
            var star = new Element('img', {'src': this.off_image, 'class': 'star-'+index});
            star.addEvent('click', this.clicked.bind(this));
            this.stars.push(star);
        }
        var stars_holder = elem.getElement('.stars');
        stars_holder.adopt(this.stars);
        this.hidden_input = elem.getElement('input');
        if (this.hidden_input.get('value'))
            this.display_stars(this.hidden_input.get('value'));
    },
    clicked: function(e) {
        var rating = e.target.get('class').replace('star-', '');
        this.display_stars(rating);
        this.hidden_input.set('value', rating);
    },
    display_stars: function(rating) {
        for (var index = 0;index < this.stars.length;index++) {
            var star = this.stars[index];
            if (index < rating)
                star.set('src', this.on_image);
            else
                star.set('src', this.off_image);
        }
    }
});

var TableExpander = new Class({
    initialize: function(table, target_selector, show_trigger_selector, hide_trigger_selector) {
        table.getElements('tbody tr').each(function(row){
            var target = row.getElement(target_selector);
            var show_trigger = row.getElement(show_trigger_selector);
            var hide_trigger = row.getElement(hide_trigger_selector);
            var first_cell = row.getElement('td');
            var initial_padding_bottom = first_cell.getStyle('padding-bottom').toInt();
            show_trigger.addEvent('click', function(e){
                e.stop();
                row.addClass('expanded');
                var target_height = target.getSize().y;
                row.getElements('td').each(function(cell){
                    cell.setStyle('padding-bottom', target_height + initial_padding_bottom + 'px');
                });
            });
            hide_trigger.addEvent('click', function(e){
                e.stop();
                row.removeClass('expanded');
                row.getElements('td').each(function(cell){
                    cell.setStyle('padding-bottom', initial_padding_bottom + 'px');
                });
            });
        });
    }
});

var OverlayHandler = new Class({
    initialize: function(name, overlay, target, close_link, dont_show_again_link, dont_show_on_hide) {
        this.no_show_cookie_days = 0;
        this.name = name;
        this.overlay = overlay;
        this.target = target;
        this.overlay.addEvent('click', function(e){this.hide();}.bind(this));
        this.dont_show_on_hide = dont_show_on_hide;
        if (close_link)
            close_link.addEvent('click', function(e){e.stop();this.hide();}.bind(this));
        if (dont_show_again_link)
            dont_show_again_link.addEvent('click', function(e){e.stop();this.show_no_more();this.hide();}.bind(this));
        this.target.getElements('a.close_after').each(function(elem){
            elem.addEvent('click', this.hide.bind(this));
        }.bind(this));
        this.target.getElements('a.no_show_after').each(function(elem){
            elem.addEvent('click', this.show_no_more.bind(this));
        }.bind(this));
    },
    show: function() {
        if (!this.readCookie(this.name + '_noshow')) {
            this.overlay.setStyle('display', 'block');
            var viewport_size = window.getScrollSize();
            this.overlay.setStyle('height', viewport_size.y + 'px');
            this.overlay.setStyle('width', viewport_size.x + 'px');
            this.overlay.addEvent('click', this.hide.bind(this));
            this.target.setStyle('display', 'block');
            var vertical_offset = (window.getSize().y - this.target.getSize().y) / 2;
            if (vertical_offset < 0)
                vertical_offset = 5;
            // For IE6 stick with postion:absolute and offset.  For other browsers
            // use position:fixed so overlay is unaffected by scroll.
            if (Browser.Engine.trident && Browser.Engine.version < 5)
                vertical_offset += $(document.documentElement).getScroll().y; 
            else
                this.target.setStyle('position', 'fixed');
            this.target.setStyle('top', vertical_offset);
        }
    },
    hide: function() {
        this.target.setStyle('display', 'none');
        this.overlay.setStyle('display', 'none');
        this.overlay.removeEvents('click');
        if (this.dont_show_on_hide)
            this.show_no_more();
    },
    show_no_more: function() {
        this.createCookie(this.name + '_noshow', 'noshow', this.no_show_cookie_days);
    },
    /* cookie functions from quirksmode.org */
    createCookie: function(name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    },
    readCookie: function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }
});

var CouponOverlayHandler = new Class({
    Extends: OverlayHandler,
    initialize: function(name, overlay, target, close_link, action_url) {
        this.parent(name, overlay, target, close_link, null);
        this.action_url = action_url;
    },
    hide: function() {
        document.location.href = this.action_url;
    }
});

var EmailOverlayHandler = new Class({
    Extends: OverlayHandler,
    initialize: function(name, overlay, target, close_link, dont_show_again_link, dont_show_on_hide) {
        this.parent(name, overlay, target, close_link, dont_show_again_link, dont_show_on_hide);
        var handler = this;
        var form = this.target.getElement('form');
        form.addEvent('submit', function(e) {
            e.stop();
            new Request.HTML({url: this.get('action'), onComplete: function(t, e, h, j) {
                handler.hide();
                handler.show_no_more();
            }}).post(form);
        });
    },
    attach: function(rows) {
        rows.each(function(row){
            row.getElements('a.offsite').each(function(elem){
                elem.addEvent('click', this.show.bind(this));
            }.bind(this));
        }.bind(this));
    },
    show: function() {
        if (!this.readCookie(this.name + '_noshow')) {
            this.parent();
            this.target.getElement('#email_box_name').focus();
        }
    }
});

var GroupSlider = new Class({
    initialize: function(groups, prev, next) {
        this.groups = groups;
        this.prev = prev;
        this.next = next;
        if (this.prev)
            this.prev.addEvent('click', this.show_prev.bind(this));
        if (this.next)
            this.next.addEvent('click', this.show_next.bind(this));
    },
    show_prev: function(e) {
        new Event(e).stop();
        this.move(-1);
    },
    show_next: function(e) {
        new Event(e).stop();
        this.move(+1);
    },
    move: function(increment) {
        var current_index = null;
        this.groups.each(function(group, index){
            if (group.hasClass('visible')) {
                current_index = index;
                group.removeClass('visible');
            }
        });
        var new_index = 0;
        if (current_index + increment >= this.groups.length || current_index + increment < 0)
            new_index = current_index;
        else
            new_index = current_index + increment;
        if (new_index == 0)
            this.prev.addClass('disabled');
        else
            this.prev.removeClass('disabled');
        if (new_index == this.groups.length - 1)
            this.next.addClass('disabled');
        else
            this.next.removeClass('disabled');
        this.groups[new_index].addClass('visible');
    }
});

var Paginator = new Class({
    initialize: function(wrapper, pager_links, page_number_display) {
        if (!wrapper)
            return;
        this.wrapper = wrapper;
        this.page_number_display = page_number_display;
        this.pages = this.wrapper.getElements('.paginate');
        this.current_page = 1;
        this.page_count = this.pages.length;
        this.page_links = [];
        pager_links.each(function(link){
            if (link.hasClass('prev')) {
                this.prev_link = link;
                link.addEvent('click', function(e){
                    new Event(e).stop();
                    this.go_prev();
                }.bind(this));
            }
            else if (link.hasClass('next')) {
                this.next_link = link;
                link.addEvent('click', function(e){
                    new Event(e).stop();
                    this.go_next();
                }.bind(this));
            }
            else {
                this.page_links.push(link);
                var page_number = this.page_links.length;
                link.addEvent('click', function(e){
                    new Event(e).stop();
                    this.go_page(page_number);
                }.bind(this));
            }
        }.bind(this));
        this.check_fragment();
    },
    check_fragment: function() {
        if (document.location.hash) {
            var page_match = document.location.hash.match(/#page-(\d+)/);
            if (page_match)
                this.go_page(parseInt(page_match[1]));
            else {
                var review_match = document.location.hash.match(/#review-(\d+)/);
                if (review_match)
                    this.go_review(parseInt(review_match[1]));
            }
            window.scrollTo(0, this.wrapper.getPosition().y - 40);
        }
    },
    go_prev: function() {
        this.go_page(this.current_page - 1);
    },
    go_next: function() {
        this.go_page(this.current_page + 1);
    },
    go_page: function(page_number) {
        if (page_number > 0 && page_number <= this.page_count) {
            this.page_number_display.set('text', page_number);
            if (this.prev_link && this.next_link) {
                if (page_number == 1)
                    this.prev_link.removeClass('active');
                else
                    this.prev_link.addClass('active');
                if (page_number == this.page_count)
                    this.next_link.removeClass('active');
                else
                    this.next_link.addClass('active');
            }
            if (this.page_links.length > 0 && this.pages.length > 0) {
                this.page_links[this.current_page-1].removeClass('active'); 
                this.page_links[page_number-1].addClass('active'); 
                this.pages[this.current_page-1].removeClass('visible');
                this.pages[page_number-1].addClass('visible');
            }
            this.current_page = page_number;
            document.location.hash = '#page-' + this.current_page;
        }
    },
    go_review: function(review_id) {
        var review = this.wrapper.getElement('#review_'+review_id);
        if (review) {
            var page = review.getParent();
            while (page && !page.hasClass('paginate'))
                page = page.getParent();
            if (page) {
                var page_index = this.pages.indexOf(page);
                if (page_index != -1)
                    this.go_page(page_index+1);
            }
        }
    }
});

/* Google Analytics code for Goal Tracking */
// Cross-browser implementation of element.addEventListener()
function addListener(element, type, expression, bubbling)
{
    bubbling = bubbling || false;

    if(window.addEventListener)    { // Standard
    element.addEventListener(type, expression, bubbling);
    return true;
    } else if(window.attachEvent) { // IE
    element.attachEvent('on' + type, expression);
    return true;
    } else return false;
}

//This is what i want to do whenever someone clicks on the page
function itHappened(evt){
    //Get the clicket element
    var tg = (window.event) ? evt.srcElement : evt.target;
    //If it is an A element
    if(tg.nodeName == 'A'){
    //And it is not an internal link
    if(tg.href.indexOf(location.host) == -1){
    //Replace all odd characters, so that it works with Analytics Niavgation analysis
    var url = tg.href.replace(/[^a-z|A-Z]/g, "_");

    var txt = tg.innerHTML.replace(/[^a-z|A-Z]/g, "_");
    var str = '/go/-' + txt + '-' + url;
    try{
    //Track it
    urchinTracker(str);
    }
    catch(err){
    //alert('error: ' + err);
    }
    }
    }
}

//Add the click listener to the document
addListener(document, 'click', itHappened);
/* end Google Analytics Goal Tracking */

