var ajaxlist = ajaxlist || {};

ajaxlist.IMG_ORDER = { "up" : "http://calampd.s3.amazonaws.com/images/site/arrow_asc.gif", "down" : "http://calampd.s3.amazonaws.com/images/site/arrow_desc.gif" };
ajaxlist.PLUS_MINUS = { "plus" : "http://calampd.s3.amazonaws.com/images/site/plus.gif", "minus" : "http://calampd.s3.amazonaws.com/images/site/minus.gif" };

ajaxlist.register_listeners = function(){
	$("#ajaxwrapper .ajaxlist_filter").unbind('click').click(function() { ajaxlist.update($(this).attr("key"), $(this).attr("val"), "set"); return false; });
	$("#ajaxwrapper .ajaxlist_remove_item").unbind('click').click(function () { ajaxlist.remove_item($(this).parent().parent(), $(this).attr("value").split('=')[1]); return false; });
	$("#ajaxwrapper .ajaxlist_check").unbind('change').change(function () { ajaxlist.checkbox_changed($(this).attr("checked"), $(this).attr("value")); return false; });
	$("#ajaxwrapper .sortable").unbind('click').click(function() { ajaxlist.update("sort_by", $(this).attr("name"), "set"); ajaxlist.update("order", "up,down", "toggle"); return false; });
	$("#ajaxwrapper .sortable").append("<img />");
	$("#ajaxwrapper a.next_page").unbind('click').click(function () { ajaxlist.update("page", "1", "+", 1); return false; });
	$("#ajaxwrapper a.prev_page").unbind('click').click(function () { ajaxlist.update("page", "1", "-", 1); return false; });
	$("#ajaxwrapper select.page").unbind('change').change(function () { ajaxlist.update("page", this.options[this.selectedIndex].value, "set"); return false; });
    $("#ajaxwrapper .ajaxinfocheckbox").unbind('change').change(function () { 
        var e = $(this);
        var checked = [];
        $('input[@type=checkbox][@checked][@name=' + e.attr('name') + ']').each( function () {
            checked.push(this.value);
        });
        $('input[@type=hidden][@name=' + e.attr('name') + ']').attr('value', checked.join(','));
    });
};

ajaxlist.parameters = {};

ajaxlist.update = function(key, value, operation, extra, norefresh) {
    var old_value = ajaxlist.parameters[key];
    var current_value = extra;
    if(operation === undefined || operation == "set") {
        ajaxlist.parameters[key] = value;
    } else if (operation == "+") {
        current_value = extra;
        if (ajaxlist.parameters.hasOwnProperty(key)) {
            current_value = parseInt(ajaxlist.parameters[key], 10);
        }
        ajaxlist.parameters[key] = current_value + parseInt(value, 10);
    } else if (operation == "-") {
        current_value = extra;
        if (ajaxlist.parameters.hasOwnProperty(key)) {
            current_value = parseInt(ajaxlist.parameters[key], 10);
        }
        ajaxlist.parameters[key] = current_value - parseInt(value, 10);
    } else if (operation == "append") {
        ajaxlist.parameters[key] += value;
    } else if (operation == "toggle") {
        value = value.split(",");
        var index = (value.indexOf(ajaxlist.parameters[key]) + 1) % value.length;
        ajaxlist.parameters[key] = value[index];
    }
    if(ajaxlist.parameters[key] != old_value) {
        ajaxlist.set_ajaxinfo_value(key, ajaxlist.parameters[key]);
        if(!norefresh) {
            return ajaxlist.refresh_page();
        }
    }
    return false;
};

ajaxlist.set_ajaxinfo_value = function(key, value) {
    $('.ajaxinfo[name=' + key + ']').attr('value', value);
};

ajaxlist.recent_hash = "";
ajaxlist.poll_hash = function () {
    if(window.location.hash==ajaxlist.recent_hash) {
        return;
    }
    ajaxlist.load_parameters_from_source(window.location.hash);
    ajaxlist.refresh_page();
    ajaxlist.recent_hash = window.location.hash;
};

ajaxlist.load_parameters_from_source = function(parameter_source) {
    var parameters = parameter_source.match(/(?:^|&)([^&=]*)=?([^&]*)/g);
    var key, value;
    for(var i = 0; i < parameters.length; i++) {
        var kv = parameters[i].substring(1, 100000).split("=", 2);
        if(kv.length == 2 && kv[0].length > 0) {
            key = decodeURIComponent(kv[0]);
            value = decodeURIComponent(kv[1]);
            ajaxlist.parameters[key] = value;
            ajaxlist.set_ajaxinfo_value(key, value);
        }
    }
};

ajaxlist.param = function(data) {
    return $.param(data).replace(/\+/g, '%20');
};

ajaxlist.get_url = window.location.pathname;
ajaxlist.refresh_page = function(url) {
	$("img.ajaxspinner").show();

    if(url === undefined) {
        url = ajaxlist.get_url;
    }

	$(".ajaxinfo").each( function() {
        if (this.value) {
            ajaxlist.parameters[this.name] = this.value;
        }
	});

	// Send get request
	$.get(url, ajaxlist.parameters, function(data){
        window.location.hash = '#' + ajaxlist.param(ajaxlist.parameters);
        ajaxlist.recent_hash= window.location.hash;
		$("#ajaxwrapper").html(data);
		/*ajaxlist.register_listeners();*/
		
		/*if (sort_by == undefined){
			sort_by = $("#ajaxwrapper th.sortable[default='on']").attr("name");
		}
		$("#ajaxwrapper .sortable[name='"+sort_by+"']").attr("selected", "yes");
		$("#ajaxwrapper .sortable[name='"+sort_by+"'] img").attr("order", order);
		$("#ajaxwrapper .sortable[name='"+sort_by+"'] img").attr("src", ajaxlist.IMG_ORDER[order]);
        */
		$("img.ajaxspinner").hide();
	});
	
	return false;
};

$(document).ready( function() {
    if($('#ajaxwrapper').length == 0) {
        return;
    }
    ajaxlist.load_parameters_from_source(window.location.search);
    ajaxlist.load_parameters_from_source(window.location.hash);
    window.location.hash = '#' + ajaxlist.param(ajaxlist.parameters);
    ajaxlist.poll_hash();
    setInterval(ajaxlist.poll_hash, 1000);
});

ajaxlist.checkbox_post_address = "/ajaxlist/";
ajaxlist.remove_item = function(row_object, value){
	var identifier = $("#ajaxwrapper").attr("identifier");
	$.post(ajaxlist.checkbox_post_address, {"action" : "remove", "identifier" : identifier, "value" : value}, 
		function () { 
			if ($(row_object).parent().children().size() == 2){
				window.location.reload( true );
			} else {
				$(row_object).remove(); 
			}
			
		}
	);
};

ajaxlist.checkbox_changed = function(state, value){
	var identifier = $("#ajaxwrapper").attr("identifier");
	
	if(state === true) {
	    action = "add";
	} else if(state === undefined) {
	    action = "remove";
	} else {
	    action = "unknown";
	}

	$.ajax({
	    url: ajaxlist.checkbox_post_address,
	    type: "POST",
	    data: {"action" : action, "identifier" : identifier, "value" : value},
	    dataType: "script"
	    });
};




$(document).ready(function (){
	$("#ajaxwrapper .sortable[default='on']").attr("selected", "yes");
	$("#ajaxwrapper .sortable[default='on'] img").attr("src", ajaxlist.IMG_ORDER["up"]).attr("order", "up");	
	$("#query_button").click(function () { ajaxlist.send_ajaxinfo("search", "#"); return false; });
	$("#query_field").keypress( function (e) { if(e.which == 13) { ajaxlist.send_ajaxinfo("search", "#"); } });
	$(".ajaxlist_clear_items").click(function () { ajaxlist.send_ajaxinfo("clear", "#"); return false; });
});


ajaxlist.toggle_options_div = function(options_div, img_div) {
    var options = document.getElementById(options_div);
    var toggle_img = document.getElementById(img_div);
    if ( options.style.display != 'none' ) {
        options.style.display = 'none';
        toggle_img.src = ajaxlist.PLUS_MINUS["plus"];
    } else {
        options.style.display = '';
        toggle_img.src = ajaxlist.PLUS_MINUS["minus"];
    }
};

ajaxlist.line_height = -1;

ajaxlist.set_line_height = function(element) {
    var temp = element.text();
    element.html('&nbsp;');
    ajaxlist.line_height = element.height();
    element.text(temp);
};


ajaxlist.resize_to_fit = function(element, no_mangle_height) {
    element = $(element);
    var current_height = element.height();
    var starting_height = element.css('height');
    var text = element.text();
    text = text.replace(/^\s+|\s+$/g,"");
    element.text(text);
    if(!no_mangle_height) {
        element.css('height', 'auto');
        if (ajaxlist.line_height == -1) {
            ajaxlist.set_line_height(element);
        }
        current_height= element.height();
        element.attr('orig_height', current_height);
    }

    
    while (current_height > ajaxlist.line_height) {
        text = text.replace(/[ .]+$/, '');    
        text = text.replace(/[^\n\r ]+$/, '...');
        element.text(text);
        current_height = element.height();
    }
    element.css('height', starting_height);
};

