var FLASH = !!(navigator.mimeTypes["application/x-shockwave-flash"]);

$(function () {
    var url = window.location.pathname.substring(1) || '/';
    $('#navigation a[href$="' + url + '"]').addClass('active');
        
    $('#search, INPUT.hint, TEXTAREA.hint').hint();
    
    $('#campaign_select').change(function () {
        var year = $(this).val();
        $('#report_links a').each(function () {
            this.search = this.search.replace(/year=\d+/, 'year=' + year);
        });
        
        if (year != 2007) {
            $('.campaign2007').hide();
            $('.campaignTeam').show();
        } else {
            $('.campaign2007').show();
            $('.campaignTeam').hide();
        }
    }).change();
    
    $('#change_year').click(function () {
        $('#campaign_select').triggerHandler('change');
    })
    
    var oa = !!($('#adminBox').length);
    
    $('#cms_images a').mouseover(function (event) {
        var link = this;
        clearTimeout(this.timer);
        this.timer = setTimeout(function () {
            var pos = $(link).offset();
            $('#img_preview').remove();
            $('body').append('<img id="img_preview" src="' + link.href + '" />');
            $('body').find('#img_preview').css({
                'top' : pos.top,
                'left' : event.clientX + 100
            });                
        }, 500);
    }).mouseout(function () {
        // console.log('removed');
        $('#img_preview').remove();
    });
    
    $('#sponsorLink').click(function () {
        // bit of a hack to get the thanks page to redirect back to the right place.
        createCookie('lasthq', window.location.pathname.substr(1), 0);
    });
    
    var $panels = $('div.central-panel');
    if ($panels.length) {
        $('fieldset.styleSelectFields a').click(function () {
            $panels.hide();
            $(this.hash).show();
            return false;
        }).hover(function () {
            $(this).click();
        }, function () {
            $panels.hide().filter(':first').show();
        });
    }
    
    $("#search,INPUT.autocomplete").autocomplete("/search", {
        extraParams: { 'ajax' : 'true' },
        delay: 200,
        width: 192,
        minChars: 2,
        formatItem: function (r) {
            if (r[1]) {
                return r[0] + ' AKA ' + r[1] + ' ' + r[2];
            } else {
                return r[0];
            }
            
        },
        formatResult: function (r) {
            return r[0];
        },
        onItemSelect: function (li) {
            if (!oa) {
                window.location = '/' + li.selectValue;
            }
        },
        selectOnly: 1,
        selectFirst: false
    });
    
    $('#searchInviteUsersBtn').click(function () {
        $.ajax({
            url: '/team',
            data: { q: $('#searchInviteUsers').val(), action: 'search' },
            success: function (html) {
                $('#tellSomeone').show();
                $('#inviteSearchResults').html(html);
            }
        });
        
        return false;
    });

    $("#admWeek INPUT.livesearch").autocomplete("/search", {
        extraParams: { 'ajax' : 'true' },
        delay: 200,
        width: 192,
        minChars: 2,
        formatItem: function (r) {
            return r[0] + ' AKA ' + r[1] + ' ' + r[2];
        },
        formatResult: function (r) {
            return r[0];
        },
        selectOnly: 1,
        selectFirst: false
    });

    if (typeof tb_remove == 'function') {
        $('A.tbClose').click(tb_remove);
    }
    
    $('a.reveal').click(function () {
        $(this.hash).slideToggle();
        return false;
    });
    
    // Tab logic
    var $tablinks = $('div.TabbedPanels').each(function () {
        var $tabs = $('div.TabbedPanelsContent', this),
            $links = $('.TabbedPanelsTabGroup a', this),
            $lis = $('.TabbedPanelsTabGroup li', this);
        
        $links.click(function () {
            $links.removeClass('TabbedPanelsTabSelected');
            $(this).addClass('TabbedPanelsTabSelected');
            $tabs.hide();
            $tabs.filter(this.hash).show();
            return false;
        });
    }).find('.TabbedPanelsTabGroup a');
    
    if ($tablinks.filter('.TabbedPanelsTabSelected').length) {
      $tablinks.filter('.TabbedPanelsTabSelected').click();
    } else {
      $tablinks.filter(':first').click();
    }
    
    $('form.uniForm :input').focus(function () {
        $(this).parents('.ctrlHolder').addClass('focused');
    }).blur(function () {
        $(this).parents('.ctrlHolder').removeClass('focused');
    });
    
    // photo upload
    $('#photoUploadForm').upload({
        // debug: true,
        complete: function (ret) {
            if (ret.match(/^error:/)) { 
                alert(ret.replace(/^error: /, ''));
            } else {
                // $('#photoUploadButton', this).hide();
                // $('#photoUploadCloseButton', this).show();
                $('#photoUploadPreview').attr('src', ret);
                $('#latestUserPhoto').attr('src', ret);
                // $('#uploadLink').hide();
                $('#allUploadedPhotos').prepend('<li><img src="' + ret + '" /></li>');
                $('ul.uploadNav').trigger('update');
            }
        }
    }).find('#photoUploadCloseButton').click(function () {
        var empty = '/images/photos/questionmark2.gif';
        
        if (/team/.test(window.location.pathname)) {
            empty = '/images/photos/mugshot-group-default.gif';
        }

        tb_remove();
        $('#photoUploadPreview').attr('src', empty);
        $('#photoUploadButton').show();
        // $('#photoUploadCloseButton').hide();
    });
    
    $('#tellafriendOverlay form').submit(function () {
        var $$ = $(this);
        
        var ok = true;
        
        var inputs = [];
        $(':input', this).each(function() {
            if (this.name == 'email' && ok) {
                ok = validate(this);
            } else if (this.name == 'name' && ok) {
                ok = validateNotEmpty(this);
            }
            inputs.push(this.name + '=' + escape(this.value));
        });
        
        if (ok) {
            $.ajax({
                data: inputs.join('&'),
                type: 'POST',
                // because we have an input called action and IE doesn't like this.getAttribute('action') (returns an object ::sigh::)
                url: $$.attr('action'), 
                timeout: 2000,
                success: function(r) { 
                    $('#tellafriendOverlay')
                        .find('#tellyourdog').html("<strong class=\"errorMessage\">Thanks, we've sent your friend an email!  Go ahead and tell more of your friends below.</strong>").end()
                        .find('input[@type="text"]').val('').end()
                        .find('#tafError').html('');
                },
                error: function(xhr, e, desc) {
                    // alert("There was a problem submitting the form: " + xhr);
                }
            });
        } else {
            $('#tafError', this).html("Please provide a valid email address and your friend's name.");
        }

        return false;
    }).find('#thanksTellMore').hide();
    
    $('#allUploadedPhotos').css('display', 'none');
    
    // large radio selection (hidden radion though)
    $('fieldset').each(function () {
        var $labels = $('label.f_radio', this);
        $labels.each(function () {
            var $label = $(this);
            var $input = $label.find('input[type=radio]').hide();
            $label.click(function () {
                $labels.removeClass('selected');
                $label.addClass('selected');
                $input.get(0).checked = true;
            });
            
        });
    });
    
    $('#battleBox form').submit(function () {
        var opts = $('input:radio', this).length/2;
        var sel = $('input:radio:checked').length;
        if (opts != sel) {
            alert('Please vote for all three battles.');
            return false;
        }
    });
    
    // filth!
    $('hr').wrap('<div class="separator"></div>').css('display', 'none');
    $('#finale .content p:first').addClass('first');
    $('#whatis .content p:not(:first)').addClass('p2');

	//grot!
	profjs.tweaks();
});



profjs = {
	tweaks: function(){
		if( $("div#rightInner div#tweetBox").length > 0 ){
			$("div#rightInner div#tweetBox li:odd").addClass("whiteHighlight");
		}

		if( $("div.newsandevents").length > 0 ){
			$("div.newsandevents div.article:last").removeClass("lhPanel");
		}
	}
}



// cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
    var date, expires;
    
	if (days) {
		date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	} else {
	    expires = "";
	}
	document.cookie = name+"="+value+expires+"; path=/";
}