$(function() {
    $('a.most-read').live('click', function() {
        var img = $(this).find("img");
        var img2 = $(this).parent().find('a.most-commented img');
        img.attr('src', img.attr('src').replace('_inactive', '_active'));
        img2.attr('src', img2.attr('src').replace('_active', '_inactive'));
        $('div#most_comments').hide();
        $('div#most_read').show();
    });
    $('a.most-commented').live('click', function() {
        var img = $(this).find("img");
        var img2 = $(this).parent().find('a.most-read img');
        img.attr('src', img.attr('src').replace('_inactive', '_active'));
        img2.attr('src', img2.attr('src').replace('_active', '_inactive'));
        $('div#most_comments').show();
        $('div#most_read').hide();
    });
    $('div.menu-green,div.menu-grey,div.menu-item').live('click', function() {
        var link = $(this).find("a");
        if ( link.length > 0 ) {
            window.location = link.attr("href");
        }
    });
    $('div.menu-green,div.menu-grey').mouseover(function() {
        $(this).find(".mainlink").css("color", "#bbbbbb");
    }).mouseout(function() {
        $(this).find(".mainlink").css("color", "#ffffff");
    });
    $('div.menu-item').mouseover(function() {
        $(this).find("a").css("color", "#666666");
    }).mouseout(function() {
        $(this).find("a").css("color", "#000000");
    });
    // Make the search form work
    $('img#search_button').live('click', function() {
        var link = $('#search-category option:selected').val();
        var string = $('#search-string').val();
        document.search.action = link+'&s='+string;
        document.search.submit();
    });
    // Make the comment form work
    $('img#post_comment').live('click', function() {
        $('#commentform').submit();
    });
    // Make the comment icons link to the comment section of the right article
    $('div.comments-img').live('click', function() {
        window.location = $('a#title-'+$(this).attr('id')).attr('href')+"#comments-section";
    });
    // Make the company index links work
    $('a.index-link').each(function() {
        $(this).attr('href', 'javascript: update_konsultregister("'+$(this).attr('id')+'");');
    });
    // Make the company index search bitton work
    $('img#search_konsult').live('click', function() {
        search_konsultregister($('input#konsult_text').val(), $('select#konsult_bransch').val());
    });
    // Make the poll bars update
    update_poll_bars();
    // Make poll bars light up onmouseover
    $("img.bar").mouseover(function() {
        $(this).css("borderColor", "#000000");
    });
    $("img.bar").mouseout(function() {
        $(this).css("borderColor", "#363636");
    });
    // Make the votes work
    $("img.bar").click(function() {
        poll_vote($(this).parent().attr('id'));
    });
    // Make the signed quotes work
    install_signed_quotes();
    update_quote();
    // Make the job registry work
    if ( $('div#konsultjobb').length > 0 ) {
        install_job_registry();
    }
});

signed_quotes = [];
function install_signed_quotes() {
    for ( var key in signerat_citat ) {
        var val = signerat_citat[key];
        var str = '<div style="display: none;" class="quote" id="quote-'+key+'"><div class="text_box"><span class="quote"><a href="'+val[3]+
            '" title="'+val[0]+'">'+val[0]+'</a></span><br/>'+
            '<span class="quotee">Signerat '+val[1]+'</span></div>'+
            '<a href="'+val[3]+'" title="'+val[0]+'">'+val[2]+'</a></div>';
        $("div#signed").append(str);
        signed_quotes.push('#quote-'+key);
    }
}

var quote = -1;
function update_quote() {
    if ( quote == -1 ) {
        quote = Math.floor(signed_quotes.length*Math.random());
    }
    quote += 1;
    if ( quote >= signed_quotes.length ) {
        quote = 0;
    }
    var entry = $(signed_quotes[quote]);
    if ( entry.length > 0 ) {
        $("#signed div.quote").not(signed_quotes[quote]).fadeOut('slow');
        entry.fadeIn('slow');
    }
    setTimeout("update_quote()", 5*1000);
}

function poll_vote(id) {
    $.ajax({
        type: "GET",
        url: "/wp-content/themes/konsult/poll_vote.php",
        dataType: "json",
        success: function(data) {
            if ( data == 1 ) {
                // Success, increase the number of answers by 1.
                var obj = $("div.answer#"+id+" span.percent");
                obj.attr("id", parseInt(obj.attr("id"))+1);
                update_poll_bars();
            } else {
                // Fail, do nothing
            }
        },
        data: {
            vote: id
        }
    });
}

function update_poll_bars() {
    var total = 0;
    var maxWidth = 75, baseWidth = 10;
    $("div.answer").each(function() {
        total += parseInt($(this).find("span.percent").attr('id'));
    })
    $("img.bar").each(function() {
        var percent;
        if ( total == 0 ) {
            percent = 0;
        } else {
            percent = parseInt($(this).parent().find('span.percent').attr('id'))/total;
        }
        $(this).parent().find("span.percent").html("("+Math.floor(percent*100)+"%)");
        $(this).width(baseWidth+percent*maxWidth);
    });
    $("div#poll div.info span.votes").html(total);
}

var special_cases = {
    'Å': 'a1',
    'Ä': 'a2',
    'Ö': 'a3'
};

function get_companies_by_initial(initial, callback) {
    if ( special_cases[initial] )
        initial = special_cases[initial];
    $.ajax({
        type: "GET",
        url: "/wp-content/themes/konsult/konsultregister.php",
        dataType: "json",
        success: callback,
        data: {
            initial: initial
        }
    });
}

function get_companies_by_search(search, bransch, callback) {
    $.ajax({
        type: "GET",
        url: "/wp-content/themes/konsult/konsultregister.php",
        dataType: "json",
        success: callback,
        data: {
            search: search,
            bransch: bransch
        }
    });
}

function get_companies_by_latest(callback) {
    $.ajax({
        type: "GET",
        url: "/wp-content/themes/konsult/konsultregister.php",
        dataType: "json",
        success: callback,
        data: {
            latest: "1"
        }
    });
}
function update_konsultregister(initial) {
    get_companies_by_initial(initial, function(data) {
        update_page(initial, data);
    });
}

function search_konsultregister(search, bransch) {
    get_companies_by_search(search, bransch, function(data) {
        update_page("Sökning: " + search, data);
    });
}

function latest_konsultregister() {
    get_companies_by_latest(function(data) {
        update_page("Senaste tillagda", data);
    });
}
function update_page(initial, data) {
    $("#konsultregister #listing").html("<div class='inner'><div class='header'></div><div class='sub'></div></div>");
    $("#konsultregister #index a.active-link").addClass("index-link").removeClass("active-link");
    $("#konsultregister #index #"+initial).addClass("active-link").removeClass("index-link");
    $("#konsultregister #listing").show().find(".header").html(initial);
    
    var str = "";
    for ( var key in data ) {
        var val = data[key];
        str += "<div class='company'><div class='name'><a href='"+val[2]+"' title='"+val[0]+"'>"+val[0]+"</a></div><div class='bransch'>&mdash; "+val[1]+"</div></div>";
    }
    if ( str == "" ) {
        str = "Inga konsulter hittades.";
    }
    $("#konsultregister #listing .sub").html(str);
}

function install_job_registry() {
    $.ajax({
        type: "GET",
        url: "/wp-content/themes/konsult/konsultjobb.php",
        dataType: "json",
        success: update_jobs,
        data: {
            latest: "1"
        }
    });
}

function update_jobs(data) {
    var str = "";
    for ( var key in data ) {
        var val = data[key];
        str += "<div class='job'><div class='name'><a href='"+val[1]+"' title='"+val[0]+"'>"+val[0]+"</a></div></div>";
    }
    if ( str == "" ) {
        str = "Inga konsultjobb hittades.";
    }
    $("#konsultjobb div.inner div.sub").html(str);
}
