﻿/// <reference path="jquery-1.3.2.min-vsdoc.js" />

function _sort_select_options($thelist) {
    var options = $thelist.find("option").get();
    options.sort(function(a, b) {
        var keyA = $(a).text().toUpperCase();
        var keyB = $(b).text().toUpperCase();
        if (keyA < keyB) return -1;
        if (keyA > keyB) return 1;
        return 0;
    });
    $.each(options, function(index, row) {
        $thelist.append(row);
    });

    // this is a dirty hack that I'm not proud of
    //// IE 7 seems to need the actual DOM options array of the select box
    ////to be altered in order for it to rerender (and thus resize) the select box.
    ////I'm creating a dummy entry at the end of the list and then removing it to trick IE
    ////into noticing the changes that have been made
    domlist = $thelist.get(0);
    domoptions = domlist.options;
    lastindex = domoptions.length;
    domlist[lastindex] = new Option("", "", false, false);
    domlist[lastindex] = null;
    // end hack
}

function shiftlist_shift_option($theoption, $newlist) {
    $theoption.appendTo($newlist);
}

function shiftlist_shift_multiple(oldlistID, newlistID) {
    $oldlist = $("#" + oldlistID);
    $newlist = $("#" + newlistID);

    $oldlist.find("option:selected").each(function() {
        shiftlist_shift_option($(this), $newlist);
    });

    $oldlist.find("option").attr("selected", "");
    $newlist.find("option").attr("selected", "");

    _sort_select_options($oldlist);
    _sort_select_options($newlist);
}

function shiftlist_shift_all(oldlistID, newlistID) {
    $oldlist = $("#" + oldlistID);

    $oldlist.find("option").attr("selected", "selected");
    shiftlist_shift_multiple(oldlistID, newlistID);
}

function establish_shiftlist_submit() {
    $("select.shiftlist_submit").parents("form").submit(function() {
        $(this).find("select.shiftlist_submit option").attr("selected", "selected");
    });
}
function establish_shiftlist_options() {
    // set up option doubleclick functionality
    $("select[class*=shiftlist_link] option").dblclick(function() {
        var parentclass = $(this).parent("select[class*=shiftlist_link]").attr("class");
        var regex = new RegExp(/shiftlist_link\[([^\]]+)\]/i);
        var result = regex.exec(parentclass);
        var linkedID = result[1];
        $(this).siblings("option").attr("selected", "");
        $(this).attr("selected", "selected");
        shiftlist_shift_multiple($(this).parent("select[class*=shiftlist_link]").attr("id"), linkedID);
    });
}
function establish_shiftlist_buttons() {
    // set up swap buttons
    $("a[rel^=shiftlist_shift]").each(function() {
        $(this).click(function() {
            fullrel = $(this).attr("rel");
            func = shiftlist_shift_multiple;
            if (fullrel.indexOf("_all") >= 0) {
                func = shiftlist_shift_all;
            }
            rawargs = fullrel.substring(fullrel.indexOf("[") + 1, fullrel.indexOf("]"));
            args = rawargs.split(",");
            func(args[0], args[1]);
            return false;
        });
    });
}
function establish_shiftlist() {
    establish_shiftlist_submit();
    establish_shiftlist_options();
    establish_shiftlist_buttons();
}

function establish_province_lists() {
    $("select[class*=provincelist]").each(function() {
        var listclass = $(this).attr("class");
        var regex = new RegExp(/provincelist\[([^\]]+)\]/i);
        var result = regex.exec(listclass);
        if ((result[1]) && ($("#" + result[1]).size() > 0)) {
            var linkedID = result[1];
            $(this).attr("linkedID", linkedID);
        } else {
            $(this).addClass("broken");
        }
    });
    $("select[class*=provincelist]").not(".broken").change(function() {
        provID = $(this).find("option:selected").eq(0).attr("value");
        $(this).addClass("updated");
        linkedID = $(this).attr("linkedID");
        $("#source" + linkedID).html("<option>Loading...</option>");
        $("#" + linkedID).html("<option>Loading...</option>");
        $.getJSON("/Provider/GetCities/" + provID,
			    function(data) {
			        linkedID = $("select.updated[class*=provincelist]").attr("linkedID");
			        if ($("#source" + linkedID).size() > 0) {
			            $("#" + linkedID).html("");
			            $linkedlist = $("#source" + linkedID);
			        } else {
			            $linkedlist = $("#" + linkedID);
			        }
			        $linkedlist.html("");
			        for (var i = 0; i < data.length; i++) {
			            $linkedlist.append('<option value="' + data[i].value + '">' + data[i].text + '</option>');
			        }
			        _sort_select_options($linkedlist);
			        establish_shiftlist_options();
			        $("select.updated[class*=provincelist]").removeClass("updated");
			    }
		    );
    });
}

function establish_erasable_fields() {
    $("input.erasable").each(function() {
        $(this).after('<img class="erasebtn" />');
        $(this).siblings(".erasebtn").attr("linkedname", $(this).attr("name"));
    });
    $(".erasebtn").attr("src", "/res/icoClear.gif").click(function() {
        var linkedname = $(this).attr("linkedname");
        $("input[name=" + linkedname + "]").attr("value", "");
        return false;
    }).css("cursor", "pointer");
    
    if (LANGUAGE == "fr") {
        $(".erasebtn").attr("alt", "Effacer");
    } else {
        $(".erasebtn").attr("alt", "Clear");
    }
}

function establish_datepicker() {
    $.datepicker.setDefaults({
        dateFormat: 'yy-mm-dd',
        showOn: 'both',
        buttonImage: '/res/icoCalendar.gif',
        buttonImageOnly: true
    });
    if (LANGUAGE == "fr") {
    	$(".datepicker").datepicker({ buttonText: 'Choisir une date', dateFormat: 'yy-mm-dd' });
    } else {
        $.datepicker.setDefaults($.datepicker.regional['']);
        $(".datepicker").datepicker({ buttonText: 'Choose a date', dateFormat: 'yy-mm-dd' });
    }
}

function establish_collapsible_areas() {
    $(".collapsing .collapsible-trigger").click(function() {
        $(this).parents(".collapsible-container").find(".collapsible-region").toggle().toggleClass("collapsed");
        $(this).toggleClass("collapsed");
    }).click();
   }

/**
 *	Setup external links to make Google Analytics calls.
*/
function establish_external_links() {
   	$("a[href^='mailto']").click(function() {
   		if (typeof pageTracker != "undefined") {
   			var address = $(this).attr('href').replace("mailto:", "");
   			pageTracker._trackPageview('/outgoing/email/' + address);
   		}
   	});
   	$("a[href^='http']").click(function() {
   		if (typeof pageTracker != "undefined") {
   			var address = $(this).attr('href').replace("https://", "").replace("http://", "");
   			var base = ($(this).closest(".newslist").size() > 0) ? '/outgoing/news/' : '/outgoing/site/';
   			pageTracker._trackPageview(base + address);
   		}
   	});
   }


   function establish_sectorarea_popups() {
   	$("[title]").css('cursor', 'pointer');
   }

var LANGUAGE = "en";

$(document).ready(function() {
	if (location.href.indexOf("/fr/") >= 0) {
		LANGUAGE = "fr";
	}
	if ($("body").hasClass("lang-fr")) {
		LANGUAGE = "fr";
	}

	establish_shiftlist();

	establish_province_lists();

	establish_erasable_fields();

	establish_datepicker();

	establish_external_links();

	$(".quickSearchRefinedForm, *[name=quickSearchRefinedForm]").addClass("collapsing");
	establish_collapsible_areas();

	establish_sectorarea_popups();
});

