Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

$(".thumbnails a").click(function(e){
     e.preventDefault();
});


// URL COMPUTATION
function checkParam (param) {
    if (params[param].length < 1) { 
        return '';
    }
    else { 
        return '&' + param + '=' + params[param] 
    };
}

var permalink = 'http://www.cataloged.cc/';

function makePermalink () {
    ids = [params['aid'], params['pid']];
    if (params['aid'] !='' && params['pid'] !='') {
        ids = 'aid=' + ids[0] + '&pid=' + ids[1];
    }
    else {
        if (params['aid'] !='') ids = 'aid=' + ids[0]
        else { ids = 'pid=' + ids[1] }
    }
    permalink = 'http://www.cataloged.cc/?'+ids
    
    if (checkParam('aid') == '' & checkParam('pid') == '') { 
        permalink = 'http://www.cataloged.cc/'  
    }
    
    $('#bookmark a').attr('href', permalink).text(permalink);
    
    if (permalink.length >= 70) {
        var urltext = permalink.substring(0,69)+'…';
        $('#bookmark a').text(urltext);
    }
    else {
        $('#bookmark a').text(permalink);
    };

    return permalink
}

function makeURL () {
    var myURL;
    myURL =  'ac='  + params['ac'];
    myURL += '&ao=' + params['ao'];
    myURL += checkParam('aid');
    myURL += '&nc=' + params['nc']; 
    myURL += '&no=' + params['no']; 
    myURL += '&pc=' + params['pc']; 
    myURL += '&po=' + params['po']; 
    myURL += checkParam('pid');
    return myURL;
}


// FOLD/UNFOLD
function fold (div, param, table, status) {
    var id = div.attr('id').split("-")[1];
    var posInPid = jQuery.inArray(parseInt(id), params[param]);
    // update params
    if (status == 'fold'){
        if (posInPid != -1){
             params[param].remove(posInPid);
             params[param].sort()
         }
    } else if (status == 'unfold'){
        if (posInPid == -1){
             params[param].push(parseInt(id))
             params[param].sort()
         }
    }
    // loading
    div.ajaxStart(function(){
        div.addClass("wait");
     });
    // send request
    $.ajax({
        url: "/ajax/"+ table +"/row/" + status +"/" + id + "/",
        success: function(html){
            var tr = div.closest("tr");
            var row1 = tr.hasClass('row1');
            var rowid = tr.attr('id'); 
            var checked = tr.find("input:checkbox:first").is(":checked");
            // 
            if (table == 'about' && status == 'fold') {
                var rowspan = tr.find('td:first').attr('rowspan');
                tr.nextAll().slice(0, rowspan-1).remove()
            };
            if (table == 'projects' && status == 'fold') {
                tr.next("tr").remove();
            };
            tr.replaceWith(html);
            // 
            var new_tr = $("#"+rowid);
            if (table == 'about' && status == 'unfold') {
                var rowspan = new_tr.find('td:first').attr('rowspan');
                var trgroup = new_tr.nextAll().slice(0, rowspan-1)
                if (row1) {
                    trgroup.addClass('row1');
                    trgroup.removeClass('row2');
                }
                else {
                    trgroup.addClass('row2');
                    trgroup.removeClass('row1');
                }
            };
            if (row1) {
                new_tr.addClass('row1');
                new_tr.removeClass('row2');
            }
            else {
                new_tr.addClass('row2');
                new_tr.removeClass('row1');
            }
            if (checked) {
                new_tr.find("input:checkbox:first").attr("checked", "checked");
            };
            makePermalink();
        }
    });
}

// CHOOSE COLUMN
function chooseColumn (div, table, paramCol, order){
    var item = div;
    var column = div.closest('th').attr('class').split(' ')[0].split('-')[1];
    if (params[paramCol] != column ) {
        params[order] = 'asc';
    }
    else {
        if (params[order] == 'asc') {
            params[order] = 'desc';
        }
        else {
            params[order] = 'asc'
        };        
    };
    params[paramCol] = column
    div.closest('a').attr('href', '?'+ makeURL()) 
    // loading
    div.ajaxStart(function(){
        div.addClass("wait");
     });
    $.ajax({
            url: "/ajax/"+ table +"/table/?"+ makeURL(),
            success: function(html){
                item.closest("table").replaceWith(html);
            }
    });
}

// CHECK ALL CHECKBOXES
function checkbox (e) {
    /*
    Check/uncheck all the checkboxes of the column
    */
    if ($(this).attr('checked')) {
        $(this).closest('table').find('.cell-cb input').each(function(i) {
            $(this).attr('checked', "true");
        })
    }
    else {
        $(this).closest('table').find('.cell-cb input').each(function(i) {
            $(this).attr('checked', "");
        })
    }
}

// AJAX
$(document).ready(function() {
    makePermalink();
    // Show big image
    $(".thumbnails .image").live("click", function(e){
        e.preventDefault();
        var snippet = new String();
        snippet += '<img src="';
        snippet += $(this).closest('a').attr('href');
        snippet += '" class="big_image + title=';
        snippet += $(this).attr('title');
        snippet += 'alt=' + $(this).attr('alt');
        snippet += '" />';
        $(this).closest('tr').find('.big_image').replaceWith(snippet);
    });
    // Show video
    $(".medias .video").live("click", function(e){
        e.preventDefault();
        var snippet = new String();
        snippet += '<object class="big_image" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="352" height="288"><param name="src" VALUE="';
        snippet += $(this).closest('a').attr('href');
        snippet += '" ><param name="wmode" value="transparent"> <param name="autoplay" value="true" ><param name="loop" value="true" ><param name="controller" value="false" ><embed src="';
        snippet += $(this).closest('a').attr('href');
        snippet += '" type="video/mp4" pluginspage="http://www.apple.com/quicktime/download" autoplay="true"  width="352" height="288" wmode="transparent" loop="true" controller=false></embed></object>';
        $(this).closest('tr').find('.big_image').replaceWith(snippet);
    });
    // Show audio
    $(".medias .audio").live("click", function(e){
        e.preventDefault();
        var snippet;
        snippet += '<object class="big_image" width="600 height="20""><param name="src" value="';
        snippet += $(this).closest('a').attr('href');
        snippet += '" type="audio/mpeg"><param name="autoplay" value="true" ><param name="controller" value="true" ><embed src="';
        snippet += $(this).closest('a').attr('href');
        snippet += '" width="600"  height="20" type="audio/mpeg" autoplay="true" controller=true></embed></object>';
        $(this).closest('tr').find('.big_image').replaceWith(snippet);
    });
    // Show Next Image
    $(".big_image").live("click", function(e){
        var Links = new Array();
        var Legends = new Array();
        $(this).closest('tr').find('.thumbnails img').each(function(i) {
            Links.push($(this).closest('a').attr('href'));
            Legends.push($(this).attr('title'));
        });
        for (var i=0; i < Links.length; i++) {
            if ($(this).attr('src') == Links[i]) {
                var index = (i+1) % Links.length;
                $(this).attr('src', Links[index]);
                $(this).attr('title', Legends[index]);
                break;
            }
        };
    });
        
////// ABOUT
    // Unfold
    $(".fold .aboutLink").live("click", function(e){
        e.preventDefault();
        fold($(this), 'aid', 'about', 'unfold');
    });

    // Fold
    $(".unfold .aboutLink").live("click", function(e){
        e.preventDefault();
        fold($(this), 'aid', 'about', 'fold');
    });

////// PROJECTS
    // Unfold
    $(".fold .itemLink").live("click", function(e){
        e.preventDefault();
        fold($(this), 'pid', 'projects', 'unfold');
    });

    // Fold
    $(".unfold .itemLink").live("click", function(e){
        e.preventDefault();
        fold($(this), 'pid', 'projects', 'fold');
    });
    
////// ORDER-BY
    $("#about .sort-bt a").live("click", function(e){
        e.preventDefault();
        chooseColumn($(this), 'about', 'ac', 'ao')
    });
    $("#news .sort-bt a").live("click", function(e){
        e.preventDefault();
        chooseColumn($(this), 'news', 'nc', 'no')
    });
    $("#projects .sort-bt a").live("click", function(e){
        e.preventDefault();
        chooseColumn($(this), 'projects', 'pc', 'po')
    });
    $("#bt-language").live("click", function(e){
        $("#i18n_next").attr('value', "/?" + makeURL())
        // e.preventDefault();
    });
    
////// IMAGE LAYER
    $("#image-layer a").click(function(e){
        e.preventDefault();
        $("#image-layer").remove()
        var id = $(this).attr('href').split("=")[1];
        // var div = $('#item-'+id)
        fold($('#item-'+id), 'pid', 'projects', 'unfold');
        // $.ajax({
        //     url: "/ajax/projects/row/unfold/" + id + "/",
        //     success: function(html){
        //         makePermalink();
        //         div.closest("tr").replaceWith(html);
        //     }
        // });
    });
    $("#image-layer").click(function(e){
        e.preventDefault();
        $(this).remove()
    });
////// CHECK-BOXES
    $('#cb-about-00').live("click", checkbox);
    $('#cb-news-00').live("click", checkbox);
    $('#cb-projects-00').live("click", checkbox);
///// ACTIONS
    $("#dropdown-selection").change(function () {
            // Uncheck all
            $('.cell-cb input').each(function(i) {
                $(this).attr('checked', "");
            });
            // Verifies if IDs matches about, news or projects
            var Values = $(this).find("option:selected").attr('value').split(',');
            for (var i=0; i < Values.length; i++) {
                var val = Values[i].substring(1,Values[i].length);
                switch (Values[i].substring(0,1)) {
                    case "A":
                        $("#cb-about-"+val).attr('checked', "checked");
                        break;
                    case "N":
                        $("#cb-news-"+val).attr('checked', "checked");
                        break;
                    case "P":
                        $("#cb-item-"+val).attr('checked', "checked");
                        break;
                };
            }
    });
    $("#submit").click(function (e) {
            e.preventDefault();
            var value = $("#dropdown-action").find("option:selected").attr('value');
            var cb = $('body').find("td input[type=checkbox]:checked")
            switch (value) {
				// FOLD ACTION
                case "fold":
                    cb.each(function(i) {
                        var row = $(this).closest("tr");
                        if (!row.hasClass('fold')) {
                            switch (row.attr('id').split('-')[0]) {
                                case "about":
                                    fold($(this).closest("td").next("td").find('a'), 'aid', 'about', 'fold');                            
                                    break;
                                case "projects":
                                    fold($(this).closest("td").next("td").find('a'), 'pid', 'projects', 'fold');                            
                                    break;
                                default:
                                    break;
                                
                            };
                        };
                    });                
                    break;
				// UNFOLD ACTION
                case "unfold":
                    cb.each(function(i) {
                        var row = $(this).closest("tr");
                        if (!row.hasClass('unfold')) {
                            switch (row.attr('id').split('-')[0]) {
                                case "about":
                                    fold($(this).closest("td").next("td").find('a'), 'aid', 'about', 'unfold');                            
                                    break;
                                case "projects":
                                    fold($(this).closest("td").next("td").find('a'), 'pid', 'projects', 'unfold');                            
                                    break;
                                default:
                                    break;
                            };
                        };
                    });
                    break;
				// GENERATE PDF ACTION
                case "pdf":
                	var selected = $("#dropdown-selection").find("option:selected").attr('text');
					aid = []
					nid = []
	                pid = []
	                
	                cb.each(function(i) {
						var table = $(this).closest("table");
						switch (table.attr('id')) {
	                    	case "about":
	                        	var id = $(this).attr('id').split("-")[2];
	                    		if (jQuery.inArray(id, aid)) { aid.push(id); } 
	                        	break;
							case "news":
	                        	var id = $(this).attr('id').split("-")[2];
	                    		if (jQuery.inArray(id, nid)) { nid.push(id); }                     
	                        	break;
	                        case "projects":
	                        	var id = $(this).attr('id').split("-")[2];
	                    		if (jQuery.inArray(id, pid)) { pid.push(id); }                     
	                        	break;
	                        default:
	                        	break;
	                        };
	                    
	                });
					if (aid.length == 0) aid = [42,16,15]
					if (nid.length == 0) url = "/pdf/?aid=" + aid + "&pid="+ pid 
					else url = "/pdf/?aid=" + aid  + "&nid=" + nid + "&pid="+ pid
	                window.open(url)
                    break;
            };
			// RESET MENUS AFTER MAKING AN ACTION
            $("#dropdown-selection option:selected").each(function(i){
                $(this).attr('selected', '');
            });
            $("#dropdown-action option:selected").each(function(i){
                $(this).attr('selected', '');
            });
            $("#dropdown-selection option:first").attr('selected', 'selected');
            $("#dropdown-action option:first").attr('selected', 'selected');
    });

});
