//var baseURL = 'http://blog.dch.co.uk/';
var baseURL = 'http://' + window.location.host + '/';

function ShowAllNavigation() {
    var loc = (window.location + '');
    loc = loc.replace(/%20/g, ' ').toLowerCase();  // do simiple white space/case treak to all

    if ($('#content div.close-category').length == 0) {
        $('#content').prepend('<div class="close-category"></div>');
    }
    else {
        $('#content div.close-category').empty();
    }

    // if it is old url format
    if (loc.indexOf('/blog.aspx?') > 0) {
        var pa = loc.substring(loc.indexOf('?') + 1);
        var pc = pa.split('&');
        var p = {};
        for (var i = 0, i_length = pc.length; i < i_length; ++i) {
            var ps = pc[i].split('=');
            if (ps.length == 2) {
                if (ps[0] != 'type') {
                    p[ps[0]] = ps[1];
                }
            }
        }

        for (var pi in p) {
            $('#content div.close-category').append(
                '<span>filtered by ' + pi + ':<em>' + p[pi].replace(' ', '-') + '</em> </span> '
            );

            // only display the first category
            break;
        }
    }
    else {
        var cats = ['/category/', '/client/', '/author/'];
        for (var i = 0, length = cats.length; i < length; ++i) {
            var cat = cats[i];
            if (loc.indexOf(cat) >= 0) {
                loc = loc.substring(loc.indexOf(cat) + cat.length);
                loc = loc.substring(0, loc.length - 5); // remove the '.aspx'

                $('#content div.close-category').append(
                    '<span>Filtered by ' + cat.substring(1, cat.length - 1) + ':<em>' + loc + '</em> </span> '
                );

                break;
            }
        }
    }

    if ($('#content div.close-category span').length > 0) {
        $('#content div.close-category')
        .append(
            $('<a class="category show-all-blog" title="Show all posts" href="javascript:void(0);">Show all posts</a>')
            .click(function () {
                window.location = baseURL;
                return false;
            })
        )
        .show();
    }

    if (loc.indexOf('/vote/') >= 0) {
        $('#content div.close-category').append('<span class="vote-thx" style="background-color:#dbdbdb;color:#623093;font-size:14px;">Thank you, and your vote is submitted.</span>');
    }
}

function TwitterFeed() {
    $('li#search label').dblclick(function () {
        if ($('ul#twitter-feed').empty().length == 0) {
            $('div#primary').append('<div id="twitter-feed-wrapper"><ul id="twitter-feed"></ul></div>');
        }

        $.ajax({
            type: "GET",
            url: "/umbraco/ajaxhandler.ashx?url=",
            dataType: "xml",
            success: function (xml) {
                $(xml).find('item').each(function () {
                    var tweet = $(this).find('title').text();
                    tweet = tweet.substring(tweet.indexOf(':') + 1);
                    $('ul#twitter-feed').append('<li>' + tweet + '</li>');
                });
            }
        });
    });
}

function HookAdvanceControl() {
    var lk = $('.entry-date');
    var loc = window.location.href;

    if (lk.length === 1) {
        lk.dblclick(function (evnt) {
            if (evnt.ctrlKey && evnt.shiftKey) {
                if (loc.indexOf('http://blog.') === 0) {
                    window.location = loc.replace('http://blog.', 'http://a.');
                }

                return false;
            }
        });

        var adminSubDomain = ['a.', 'c.'];
        for (var i = 0, length = adminSubDomain.length; i < length; ++i) {
            if (loc.indexOf('http://' + adminSubDomain[i]) === 0) {
                if ($('#LiveEditingToolbar').length === 0 && $('#login-frame').length === 0) {
                    $('.hentry').prepend('<iframe id="login-frame" scrolling="no" frameborder="0" allowtransparency="true" style="border: medium none; overflow: hidden; width: 500px; height: 390px; position: relative; top: -50px;" src="http://'
                        + adminSubDomain[i] + 'dch.co.uk/umbraco/login.aspx?redir=%2fumbraco%2fumbraco.aspx"></iframe>');
                }
            }
        }
    }
}

function RefreshIfNeed() {
    var loc = window.location.href;
    if ($('#LiveEditingToolbar').length === 0) {
        window.location = loc;  // refresh the window to bring in the control
    }
}

$(function () {
    if ($('#LiveEditingToolbar').length > 0) {
        parent.RefreshIfNeed();
    }

    $('#comments .commentlist > li > p').each(function () {
        $(this).html($(this).html().replace(/(http:\/\/[^ <]+)/, "<a href='$1' target='_blank' title='click me'>$1</a>"));
    });

    $('.entry-meta .tag-links').each(function () {
        var wrapper = $(this).parents('.hentry').eq(0);
        var authorWidth = $('.entry-meta .author', wrapper).width() + 15;
        if ($(this).width() + authorWidth > 510) {
            $(this).width(510 - authorWidth + 'px');
            wrapper.height(wrapper.height() + $(this).height() - 35 + 'px');
        }
    });

    $('div#primary li h3').click(function () {
        var that = this;

        $(that).parents('div#primary:eq(0) ul').each(function () {
            $('ul', this).not($(that).parent().find('ul')).hide('slow');
            $('h3', this).not(that).find('a').removeClass('expanded');
        });

        $('a', this).toggleClass('expanded')
        .parents('li:eq(0)').find('ul').toggle('display');
    });

    $('.bookmark-toggle').click(function () {
        $(this).parents('.left-panel:eq(0)').find('.social-icons')
            .toggle('display');
        $('.social-icons').hide();
        return false;
    });

    $('div.post').click(function () {
        $('.social-icons').hide();
    });

    // make the search box work when enter pressed
    $('.seach-wrapper input:text').keydown(function (eventObject) {
        // console.log(eventObject.keyCode);
        // enter pressed
        if (eventObject.keyCode == 13) {
            window.location = baseURL + 'search.aspx?type=blog&search=' + $(this).val();
            return false;
        }
    });

    $('.seach-wrapper a.button').click(function () {
        var searchTerm = $(this).parent().find('input:text').val();
        if (searchTerm) // will add the blank judgement here
        {
            window.location = baseURL + 'search.aspx?type=blog&search=' + searchTerm;
        }
        return false;
    });

    // use javascript to stop robot from voting...
    $('a.vote').each(function () {
        if (this.href.indexOf('/vote/') < 0) {
            // alert(this.href);
            this.href = '/blog/vote/' + ($(this).hasClass('voteYes') ? 'yes' : 'no')
            + '/' + $(this).attr('rel') + '.aspx';
            $(this).attr('target', '_blank');
        }
    });

    ShowAllNavigation();
    HookAdvanceControl();
    TwitterFeed();
});


function SetGravatar(s_imgId, s_email, i_size) {
    jQuery.get("/base/blog4umbraco/GetGravatarImage/" + s_email + ".aspx",
       function (data) {
           var avatar = jQuery("#" + s_imgId);
           if (data != "") {
               var src = "http://www.gravatar.com/avatar/" + data + "?s=" + i_size;
               avatar.src(src).show();
           } else {
               avatar.hide();
           }
       });
}

function CreateComment(s_name, s_email, s_website, s_comment, i_pageId) {
    jQuery.get("/base/blog4umbraco/CreateComment/" + i_pageId + ".aspx", { name: s_name, email: s_email, website: s_website, comment: s_comment },
       function (data) {
           alert("Data Loaded: " + data);
       });
}


/*
* SWFUpload jQuery Plugin v1.0.0
*
* Copyright (c) 2009 Adam Royle
* Licensed under the MIT license.
*
*/

(function ($) {
    var defaultHandlers = ['swfupload_loaded_handler', 'file_queued_handler', 'file_queue_error_handler', 'file_dialog_start_handler', 'file_dialog_complete_handler', 'upload_start_handler', 'upload_progress_handler', 'upload_error_handler', 'upload_success_handler', 'upload_complete_handler', 'queue_complete_handler'];
    var additionalHandlers = [];

    $.fn.swfupload = function () {
        var args = $.makeArray(arguments);
        return this.each(function () {
            var swfu;
            if (args.length == 1 && typeof (args[0]) == 'object') {
                swfu = $(this).data('__swfu');
                if (!swfu) {
                    var settings = args[0];
                    var $magicUploadControl = $(this);
                    var handlers = [];
                    $.merge(handlers, defaultHandlers);
                    $.merge(handlers, additionalHandlers);
                    $.each(handlers, function (i, v) {
                        var eventName = v.replace(/_handler$/, '').replace(/_([a-z])/g, function () { return arguments[1].toUpperCase(); });
                        settings[v] = function () {
                            var event = $.Event(eventName);
                            $magicUploadControl.trigger(event, $.makeArray(arguments));
                            return !event.isDefaultPrevented();
                        };
                    });
                    $(this).data('__swfu', new SWFUpload(settings));
                }
            } else if (args.length > 0 && typeof (args[0]) == 'string') {
                var methodName = args.shift();
                swfu = $(this).data('__swfu');
                if (swfu && swfu[methodName]) {
                    swfu[methodName].apply(swfu, args);
                }
            }
        });
    };

    $.swfupload = {
        additionalHandlers: function () {
            if (arguments.length === 0) {
                return additionalHandlers.slice();
            } else {
                $(arguments).each(function (i, v) {
                    $.merge(additionalHandlers, $.makeArray(v));
                });
            }
        },
        defaultHandlers: function () {
            return defaultHandlers.slice();
        },
        getInstance: function (el) {
            return $(el).data('__swfu');
        }
    };

})(jQuery);
