var num_tbl_sorters = 0;
$(function () {
	$.ajaxSetup({
        error: function(x, e) {
			dlog(e);
        }
    });
/*
    $.fn.qtip.styles.tornado = {
        background:'#f7f7f7',
        border:{
            width:3,
            radius:3,
            color:'#8b8b8b',
        },
        width:{
            min:60
        }
    }
    $.fn.qtip.styles.info = {
       border: {
          width: 3,
          radius: 3,
          color: '#bbdbe0'
       },
       background: '#ecf9ff',
       color: '#0888c3'
    }
    $.fn.qtip.styles.error = {
       border: {
          width: 3,
          radius: 3,
          color: '#e9c59b'
       },
       background: '#ffecce',
       color: '#e3302c'
    }
    $.fn.qtip.styles.success = {
       border: {
          width: 3,
          radius: 3,
          color: '#bfde84'
       },
       background: '#edfbd8',
       color: '#508600'
    }
    $.fn.qtip.styles.warning = {
       border: {
          width: 3,
          radius: 3,
          color: '#e5e181'
       },
       background: '#fefde2',
       color: '#666'
    }
*/
    $(".has_tooltip").tooltip({tooltip_name:'has_tooltip'});
    tablesorterInit();
    init_page_styles();
});

// elements should be jquery array
function texteditor_init(settings, elements){
    var converter = Markdown.getSanitizingConverter();
    elements.each(function(i,element){
        var el = $(element);

        /*
            This is a hack for Firefox so it doesn't throw up
            when trying to initialize the WMD Editor on a
            hidden Textarea
        */
        if (!el.is(':visible')){
            el.hide();
        }
        /* End hack */
        var old_id = el.attr('id');

        var ta_wrapper = $('<div class="wmd-panel"></div>');
        var ta_buttonbar = $('<div id="wmd-button-bar-'+ old_id +'">');
        var ta_preview = $('<h4>Text Preview</h4><div class="wmd-preview" id="wmd-preview-'+ old_id +'">');
        ta_buttonbar.wrap(ta_wrapper);

        el.attr('id',"wmd-input-" + old_id);

        el.wrap(ta_wrapper);
        ta_buttonbar.insertBefore(el);
        ta_preview.insertAfter(el);

        var editor = new Markdown.Editor(converter, "-"+old_id);
        editor.hooks.chain("onPreviewRefresh", function () {
            if(el.val().length > 0){
                ta_preview.show();
            } else {
                ta_preview.hide();
            }
        });
        editor.run();

        /*
            Show text area again to bypass FF bug
        */
        el.show();
    });
}
// elements should be jquery array
function tinymce_remove(elements){

}
// elements should be jquery array
function save_tinymce(elements, clear){

}

function tablesorterInit(){
    var monthNames = {"Jan":"01","Feb":"02","Mar":"03","Apr":"04","May":"05","Jun":"06","Jul":"07","Aug":"08","Sep":"09","Oct":"10","Nov":"11","Dec":"12"};
    $.tablesorter.addParser({
      id: 'monthDayYear',
      is: function(s) {
          //return false to turn off auto-detect
          return /^(\w{3})[ ](\d{1,2}),[ ](\d{4})$/.test(s);
      },
      format: function(s) {
          var date = s.match(/^(\w{3})[ ](\d{1,2}),[ ](\d{4})$/);
          var m = monthNames[date[1]];
          var d = String(date[2]);
          if (d.length == 1) {d = "0" + d;}
          var y = date[3];
          return '' + y + m + d;
      },
      type: 'numeric'
    });
}

function disableLinks(section){
    if (section && typeof(section) == 'string' && section!=''){
        section += ' ';
        $(section+'a[href=""]').click(function(event){event.preventDefault()});
    } else if(typeof(section) == 'object') {
        $(section).find('a[href=""]').click(function(event){event.preventDefault()}); // this probaby works for string/object...need to test
    } else {
        $('a[href=""]').click(function(event){event.preventDefault()});
    }
}

function init_section_styles(section){
    disableLinks(section);

    if (section && typeof(section) == 'string' && section!=''){
        section += ' ';
    }
    var converter = Markdown.getSanitizingConverter();
    /*$(section + "textarea[readonly=readonly]").each(function(i, el){
        var html = $(el).val();
        html = converter.makeHtml(html);
        $(el).replaceWith($('<div class="readonly_text">'+html+'</div>'));
    });*/

    // Sort table
    if (section && section != ""){
        section += " ";
    }

    $(section + "table.sortable").each(function(i,el){
		if ($(el).hasClass('no_page'))
		{
			$(el).tablesorter({
				widgets: ['zebra'],
			})
		}else
		{
			var pg_id = "pagination_holder_" + num_tbl_sorters;
			var ht = [
					'<div class="pagination pagination_holder" id="'+pg_id+'">',
						'<form>',
							'<a href="" class="first">First</a>',
							'<a href="" class="prev">Prev</a>',
							'<input type="text" class="pagedisplay" readonly="readonly" style="width:40px;">',
							'<a href="" class="next">Next</a>',
							'<a href="" class="last">Last</a>',
							'<select class="pagesize">',
								'<option selected="selected" value="10">10</option>',
								'<option value="20">20</option>',
								'<option value="30">30</option>',
								'<option value="40">40</option>',
							'</select>',
						'</form>',
					'</div>'
			];
			if(!$(el).next("div.pagination_holder").is(":empty")){
				$(el).after(ht.join(''));
			}
			$(el).tablesorter({
				widgets: ['zebra'],
			}).tablesorterPager({
				container:$('#'+pg_id),
				positionFixed:false
			});
			num_tbl_sorters++;
		}

    });

    //dlog($(section + "table.sortable tfoot div.pagination_holder"));



    // Check / uncheck all checkboxes
    $(section + '.check_all').click(function() {
        $(this).parents('form').find('input:checkbox').attr('checked', $(this).is(':checked'));
    });

    // Modal boxes - to all links with rel="facebox"
    $(section + 'a[rel*=facebox]').facebox()


    // Messages
    init_message_style(section + '.message');


    // Form select styling
    $(section + "form select").select_skin();


    $(section + "ul.tabs li").click(function() {
        $(this).parent().find('li').removeClass("active");
        $(this).addClass("active");
        $(this).parents('.block').find(".tab_content").hide();

        var activeTab = $(this).find("a").attr("href");
        $(activeTab).show();
        return false;
    });
     // Style file input
    /*$(section + "input[type=file]").filestyle({
        image: $MEDIA_URL+"images/upload.gif",
        imageheight : 30,
        imagewidth : 80,
        width : 250
    });*/
    // Date picker
    $(section + 'input.date_picker:not([readonly])').date_input({
        dateToString:function(date){
            var s = date.toDateString()
            s = s.substr(3, s.length);
            s = s.substr(1,6) + ', ' + s.substr(8, s.length);
            return s;
        }
    });
    /*$(section + 'input.date_picker[readonly]').addClass('readonly');
    $(section + 'input.date_picker').attr('readonly',"readonly");*/
}

function init_message_style(msg){
    if(!$(msg).hasClass('nofade')){
        $(msg).hide();
    }
    if(!$(msg).hasClass('noclose')){
        if($(msg).find('span.close').length == 0){
            $(msg).append('<span class="close" title="Dismiss"></span>');
        }
        $(msg + ' .close').hover(
            function() { $(this).addClass('hover'); },
            function() { $(this).removeClass('hover'); }
        );

        $(msg + ' .close').click(function() {
            $(this).parent().fadeOut('slow', function() { $(this).remove(); });
        });
    }
    if(!$(msg).hasClass('nofade')){
        $(msg).fadeIn('slow');
    }
}

function init_sidebar_styles(){
	// Sidebar Tabs
    $(".sidebar_content").hide();

    if(window.location.hash && window.location.hash.match('sb')) {

        $("ul.sidemenu li a[href="+window.location.hash+"]").parent().addClass("active").show();
        $(".block .sidebar_content#"+window.location.hash).show();
    } else {

        $("ul.sidemenu li:first-child").addClass("active").show();
        $(".block .sidebar_content:first").show();
    }

    $("ul.sidemenu li").click(function() {

        var activeTab = $(this).find("a").attr("href");
        window.location.hash = activeTab;

        $(this).parent().find('li').removeClass("active");
        $(this).addClass("active");
        $(this).parents('.block').find(".sidebar_content").hide();
        $(activeTab).show();
        return false;
    });
}

function init_page_styles(){
    // Preload images
    $.preloadCssImages();

    // Profile Tooltip

    // CSS tweaks
    $('#header #nav li:last').addClass('nobg');
    $('.block_head ul').each(function() { $('li:first', this).addClass('nobg'); });
    $('.block form input[type=file]').addClass('file');


    $('.block table tr th.header').css('cursor', 'pointer');



         // Tabs
    $(".tab_content").hide();
    $("ul.tabs li:first-child").addClass("active").show();
    $(".block").find(".tab_content:first").show();








    // Sidebar Tabs
    $(".sidebar_content").hide();

    if(window.location.hash && window.location.hash.match('sb')) {

        $("ul.sidemenu li a[href="+window.location.hash+"]").parent().addClass("active").show();
        $(".block .sidebar_content#"+window.location.hash).show();
    } else {

        $("ul.sidemenu li:first-child").addClass("active").show();
        $(".block .sidebar_content:first").show();
    }

    $("ul.sidemenu li").click(function() {

        var activeTab = $(this).find("a").attr("href");
        window.location.hash = activeTab;

        $(this).parent().find('li').removeClass("active");
        $(this).addClass("active");
        $(this).parents('.block').find(".sidebar_content").hide();
        $(activeTab).show();
        return false;
    });



    // Block search
    $('.block .block_head form .text').bind('click', function() { $(this).attr('value', ''); });


    // Image actions menu
    $('ul.imglist li').hover(
        function() { $(this).find('ul').css('display', 'none').fadeIn('fast').css('display', 'block'); },
        function() { $(this).find('ul').fadeOut(100); }
    );


    // Image delete confirmation
    $('ul.imglist .delete a').click(function() {
        if (confirm("Are you sure you want to delete this image?")) {
            return true;
        } else {
            return false;
        }
    });





    // File upload
    if ($('#fileupload').length) {
        new AjaxUpload('fileupload', {
            action: 'upload-handler.php',
            autoSubmit: true,
            name: 'userfile',
            responseType: 'text/html',
            onSubmit : function(file , ext) {
                    $('.fileupload #uploadmsg').addClass('loading').text('Uploading...');
                    this.disable();
                },
            onComplete : function(file, response) {
                    $('.fileupload #uploadmsg').removeClass('loading').text(response);
                    this.enable();
                }
        });
    }


    // Navigation dropdown fix for IE6
    if(jQuery.browser.version.substr(0,1) < 7) {
        $('#header #nav li').hover(
            function() { $(this).addClass('iehover'); },
            function() { $(this).removeClass('iehover'); }
        );
    }
    init_section_styles("");
    // IE6 PNG fix
    $(document).pngFix();
}

$(document).ready(function(){
    $(".add_more").live("click", function(e){
        e.preventDefault();
        form = $(this).parents("form");
        table = form.find(".main_table");

        var newElement = form.find(".main_tr:last").clone();
        // TODO NOTE: The prefex is fron the add button's id
        var prefex = $(this).attr('id');
        var total = form.find("#id_"+prefex+"-TOTAL_FORMS").val();
        newElement.find(':input').each(function(){
            var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
            var id = 'id_' + name;
            $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
            $(this).parent('.main_td').removeClass('form_error');
        });

        newElement.find('select').each(function(){
            var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
            var id = 'id_' + name;
            $(this).attr({'name': name, 'id': id});
            $(this).parents('.main_td').removeClass('form_error');
        });
        total++;
        form.find("#id_"+prefex+"-TOTAL_FORMS").val(total);
        form.find(".main_tr:last").after(newElement);
        form.find(".main_tr:last select").select_unskin();
        form.find(".main_tr:last select").select_skin();
        form.find(".date_picker").date_input();

        /*form = $(this).parents("form");
        table = form.find(".main_table");
        clone = form.find(".main_tr:last").clone();
        clone.appendTo(table);
        form.find(".main_tr:last .main_td input").each(function(){
            $(this).val("");
            if($(this).attr('checked')){ $(this).attr('checked', false) }
        });
        table.append('<tr class="main_tr"></tr>');
        tr = table.find(".main_tr:last")
        tr.append("<td></td>");
        form.find(".date_picker").date_input();
        //$("select").select_skin();
        prefex = $(this).attr('id');
        total = form.find("#id_"+prefex+"-TOTAL_FORMS");
        count = total.val();
        total.val(parseInt(count)+1);*/
    });
});

$('a.button_disabled').live('click', function(e){
    e.preventDefault();
});

