/** NAMESPACE **/
if (!window.FSN) {
    FSN = {};
}


/*********************************************/
/*******   PAGE CONTROLLER   *****************/
/*********************************************/

jQuery(function() {

    /*** INIT ***/
    var UPDATE_PROGRESS_MIN_SHOW_TIME = 500;
    var updateProgress = jQuery(".UpdateProgress");
    var requestStartTime = 0;

    initPage();

    /*** FUNCTIONS ***/
    function initPage() {
        if (updateProgress.length < 1) { return; }
        initUpdateProgress();
        initInfoBox();
        addDotNetRequestHandlers();
    }
    function addDotNetRequestHandlers() {
        jQuery("#tabell").bind("tableLoading", handleBeginRequest);
        jQuery("#PanelBehandlingsstedInfo").bind("infoLoading", handleBeginRequest);
        jQuery("#tabell").bind("tableReady", handleEndRequest);
        jQuery("#PanelBehandlingsstedInfo").bind("infoReady", handleEndRequest);
    }
    function handleBeginRequest(sender, args) {
        layoutUpdateProgress();
        updateProgress.show();
        requestStartTime = getTime();
    }
    function handleEndRequest(sender, args) {
        layoutInfoBox();
        var requestTime = getTime() - requestStartTime;
        var wait = Math.max(0, UPDATE_PROGRESS_MIN_SHOW_TIME - requestTime);
        window.setTimeout(function() { updateProgress.hide() }, wait);
    }
    function initUpdateProgress() {
        updateProgress._bg = updateProgress.find(".background");
        updateProgress._bg_width = updateProgress._bg.width();
        updateProgress._bg_height = updateProgress._bg.height();
        updateProgress._icon = updateProgress.find(".icon");
        updateProgress._icon_width = updateProgress._icon.width();
        updateProgress._icon_height = updateProgress._icon.height();
        updateProgress._text = updateProgress.find(".text");
        updateProgress._text_width = updateProgress._text.width();
        updateProgress._text_height = updateProgress._text.height();
        updateProgress.hide();
        layoutUpdateProgress();
    }
    function layoutUpdateProgress() {
        var wp = jQuery.viewportSize();
        updateProgress.fillViewport();
        updateProgress.css({
            top: getScroll() + "px"
        });
        updateProgress._bg.css({
            left: (wp.width / 2) - (updateProgress._bg_width / 2) + "px",
            top: (wp.height / 2) - (updateProgress._bg_height / 2) + "px"
        });
        updateProgress._icon.css({
            left: (wp.width / 2) - (updateProgress._icon_width / 2) + "px",
            top: (wp.height / 2) - (updateProgress._icon_height * 1.5) + "px"
        });
        updateProgress._text.css({
            left: (wp.width / 2) - (updateProgress._text_width / 2) + "px",
            top: (wp.height / 2) - (updateProgress._text_height / 2) + "px"
        });
    }

    function initInfoBox() {
        var infobox = jQuery("#PanelBehandlingsstedInfo");
        var innhold = jQuery(".middle", infobox);
        var overskrift = jQuery("div.heading h1 span", innhold);
        var kontaktinfo = jQuery(".contact", innhold);
        var informasjon = jQuery(".info", innhold);

        var opplysninger = jQuery("#opplysninger");

        jQuery("#infoLinkVentetider", informasjon).click(function() { jQuery("input[value='ventetider']", opplysninger).click(); return false; });
        jQuery("#infoLinkSamletKvalitet", informasjon).click(function() { jQuery("input[value='samlet']", opplysninger).click(); return false; });
        jQuery("#infoLinkIndikatorer", informasjon).click(function() { jQuery("input[value='indikatorer']", opplysninger).click(); return false; });
        jQuery("#infoLinkErfaringer", informasjon).click(function() { jQuery("input[value='erfaringer']", opplysninger).click(); return false; });

        jQuery(document).bind("click", function(event) {
            var clicked = jQuery(event.target);
            if (isLinkOrDescendantOfLink(clicked) && !clicked.hasClass("close")) { return; }
            if (infobox.length == 1 && infobox.hasClass("shown")) {
                event.preventDefault();
                infobox.addClass("hidden").removeClass("shown");
            }
        });

        function fyllInfoBox(resultat) {
            overskrift.text(resultat.Navn);
            jQuery(".telefon span", kontaktinfo).text(resultat.Telefon);
            jQuery(".telefax span", kontaktinfo).text(resultat.Telefax);
            jQuery(".epost a", kontaktinfo).attr("href", "mailto:" + resultat.EPost).text(resultat.EPost);
            jQuery(".postadresse span:nth-child(1)", kontaktinfo).text(resultat.Adresse);
            jQuery(".postadresse span:nth-child(2)", kontaktinfo).text(resultat.Postnummer);
            jQuery(".postadresse span:nth-child(3)", kontaktinfo).text(resultat.Poststed);
            jQuery(".besoksadresse span", kontaktinfo).text(resultat.Besoksadresse);
            jQuery(".hjemmeside a", kontaktinfo).attr("href", resultat.Hjemmeside).text(resultat.Hjemmeside);
            jQuery(".behandlingsstedInfo span", informasjon).text(resultat.Informasjon);

            var behandlingsIdmatch = /(\&|\?)BehEnhetId=.*?(\&|$)/;
            var fagtypematch = /\&BehEnhetType=.*?$/;
            var typeInstmatch = /\&typeInst=.*?$/;

            var alleKvalitetsindikatorer = jQuery(".alleKvalitetsindikatorer a", informasjon);
            var kvalIndUrl = alleKvalitetsindikatorer.attr("href");
            alleKvalitetsindikatorer.attr("href", kvalIndUrl.replace(behandlingsIdmatch, "&BehEnhetId=" + resultat.ID + "&").replace(fagtypematch, "&BehEnhetType=" + resultat.Fagtype));

            var alleVentetider = jQuery(".alleVentetider a", informasjon).first();
            var ventetiderUrl = alleVentetider.attr("href");
            alleVentetider.attr("href", ventetiderUrl.replace(behandlingsIdmatch, "&BehEnhetId=" + resultat.ID + "&").replace(typeInstmatch, "&typeInst=" + resultat.Fagtype));

            var rssVentetider = jQuery(".alleVentetider a", informasjon).last();
            var rssUrl = rssVentetider.attr("href");
            rssVentetider.attr("href", rssUrl.replace(behandlingsIdmatch, "?BehEnhetId=" + resultat.ID));

            if (resultat.Fagtype == "1") {
                jQuery(".opplysninglinker li", informasjon).removeClass("hidden");
            } else if (resultat.Fagtype == "2" || resultat.Fagtype == "3") {
                var opplysningslinker = jQuery(".opplysninglinker li", informasjon).not(":last").addClass("hidden");
            }

            if (resultat.Fagtype == "4") {
                jQuery("div.kvalitet", informasjon).addClass("hidden");
            } else {
                jQuery("div.kvalitet", informasjon).removeClass("hidden");
            }


            infobox.trigger("infoReady");
            infobox.removeClass("hidden").addClass("shown");
        }

        FSN.visBehandlingssted = function(behandlingsstedId) {
            infobox.trigger("infoLoading");
            var url = "/FSN_Webservices.svc/Behandlingssteder/" + behandlingsstedId;
            FSN.sendAjaxRequest(url, fyllInfoBox);
        }
    }

    function isLinkOrDescendantOfLink(clicked) {
        var result = false;
        if (clicked.is("a")) {
            result = true;
        } else if (clicked.parents("a").size() > 0) {
            result = true;
        }
        return result;
    }
    function layoutInfoBox() {
        var box = jQuery(".BehandlingsstedInfo");
        if (box.size() == 0) { return; }
        var body = jQuery(document.body);
        var scroll = getScroll();
        var width = box.width();
        var height = box.height();
        var wp = jQuery.viewportSize();
        var top = (scroll + (wp.height / 2) - (height / 2));
        if (top < 0) { top = 0; }
        box.css({
            left: ((wp.width / 2) - (width / 2)) + "px",
            top: top + "px"
        });
    }
    function getTime() {
        return (new Date()).getTime();
    }
    function getScroll() {
        if (self.pageYOffset) {
            return self.pageYOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {
            return document.documentElement.scrollTop;
        } else if (document.body) {
            return document.body.scrollTop;
        }
    }
});




/*********************************************/
/*******   JQUERY PLUGINS    *****************/
/*********************************************/

jQuery.fn.fillViewport = function() {
    var element = jQuery(this.eq(0));
    if( "absolute" != element.css("position") ) { return; }
    var wp = jQuery.viewportSize();
    element.css({
        left: 0,
        top:  0,
        width: wp.width+"px",
        height: wp.height+"px"
    });
    
}

jQuery.viewportSize = function() {
    var height = 0;
    var width = 0;
    if (document.documentElement != null) {
        height = document.documentElement.offsetHeight;
        width = document.documentElement.offsetWidth - 50;
    } else {
        var body = jQuery(document.body);
        width = body.width();
        height = body.height();
    }
    return { width: width, height: height };
}

jQuery.fn.initSearchAutoComplete = function(tjenester) {
    jQuery(this).autocomplete(tjenester, {
        minChars: 2,
        width: 292,
        max: 15,
        matchContains: true,
        autoFill: false,
        formatItem: function(row) {
	        return row.text;
        },
        formatMatch: function(row) {
	        return row.text;
        },
        formatResult: function(row) {
            return row.text;
        }
    });  
   	jQuery(this).result(function(event, data, formatted){
        var toString = window.location.href;
        window.location = toString.replace(/(#|\?).*/g, '') + "?p=" + data.ID;
    });

}

jQuery.fn.initTabs = function() {
    var opplysninger = jQuery(this);
    var items = jQuery("span", opplysninger);
    jQuery("#FilterDropdownContent div").not(":last").bind('valueChanged', behandlingEndret);


    items.click(function(event) {
        if (opplysninger.is(".disabled")) { return; }
        var valgt = jQuery(this);
        if (!erAktivFane(valgt)) {
            oppdaterValgt(valgt);
            opplysninger.trigger('valueChanged');
            oppdaterSynligeFanerBasertPaaValgtFane();
        }

    });

    jQuery.fn.refreshTabs = function() {
        behandlingEndret();
    }

    function behandlingEndret(event) {
        opplysninger.removeClass("disabled").addClass("disabled");
        oppdaterValgt(jQuery("span:first", opplysninger));
        var valgtBehandling = FSN.GetValgtBehandling();
        if (valgtBehandling == 1) {
            settSynligeFaner(true, true, false, false);
        } else if (valgtBehandling == 4) {
            settSynligeFaner(true, false, false, false);
        } else {
            settSynligeFaner(true, false, false, true);
        }

        if (valgtBehandling == 2) {
            settErfaringnavn("Brukererfaringer");
        } else {
            settErfaringnavn("Pasienterfaringer");
        }
    }

    function settErfaringnavn(navn) {
        jQuery("span:last>label>a", opplysninger).html(navn);
    }

    function oppdaterSynligeFanerBasertPaaValgtFane() {
        var valgtBehandling = FSN.GetValgtBehandling();
        if (valgtBehandling != 1) { return; } // ikke fysisk helse
        if (jQuery(".selected", opplysninger).is(":first-child")) {
            settSynligeFaner(true, true, false, false);
        }
        else {
            settSynligeFaner(true, true, true, true);
        }
    }

    function settSynligeFaner(forste, andre, tredje, fjerde) {
        settSynlig(jQuery("span:nth-child(1)", opplysninger), forste);
        settSynlig(jQuery("span:nth-child(2)", opplysninger), andre);
        settSynlig(jQuery("span:nth-child(3)", opplysninger), tredje);
        settSynlig(jQuery("span:nth-child(4)", opplysninger), fjerde);
    }

    function settSynlig(element, synlig) {
        if (synlig) {
            element.removeClass("hidden");
        } else {
            element.addClass("hidden");
        }
    }

    function erAktivFane(element) {
        return element.hasClass("selected");
    }

    function oppdaterValgt(element) {
        items.removeClass("selected")
        element.addClass("selected");
    }
};

FSN.sendAjaxRequest = function(url, successCallback) {
    jQuery.ajax({
        type: "GET",
        url: url,
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        dataType: "json",
        success: successCallback,
        error: function(XMLHttpRequest, textStatus, errorThrown) { alert("Error!\nText status: " + textStatus + "\nError thrown: " + errorThrown + "\nUrl: " + url); }
    });
};

FSN.GetValgtBehandling = function(){
    return jQuery("#FilterDropdownContent div:nth-child(1) span.selected input").val();
}

FSN.GetValgtFagomraade = function() {
    var fagomraade = jQuery("#FilterDropdownContent div:nth-child(2) span.selected input").val();
    if (fagomraade) {
        return fagomraade;
    }
    return "";
}

FSN.GetValgtTjeneste = function() {
    return jQuery("#FilterDropdownContent div:nth-child(3) span.selected input").val();
}

FSN.GetValgteRegioner = function() {
    return jQuery("#FilterDropdownContent div:nth-child(4) span.selected input").val();
}

FSN.GetValgtOpplysning = function() {
    return jQuery("#opplysninger span.selected input").val();
}

// Will cause the default FSN functionality, followed by 'func' (if it is non-null), to be executed each time an autocomplete operation completes in the element whose id is 'item'.
// The default functionality is to assign the value that corresponds to the selected item (see the comment for FSN.autocomplete) to the hidden field for the fsn:AutocompleteField.
FSN.setAutocompletionResultFunctionality = function(item, func) {
    $(item).result(function(event, data, formatted) {

        var selectedItem = eval("(" + data + ")");
        var valuefieldid = $(this).attr("valuefieldid");
        $("#" + valuefieldid).attr("Value", selectedItem.value);

        if (func != null)
            func(event, data, formatted);

        if ($(item).caret) {
            $(item).caret(0); // After autocompletion, move the caret to the left so that the user can see the beginning of the string in case it is too long (explicit requirement)
        }
    });
}

// Gives autocomplete functionality to an fsn:AutocompleteField (modified text box). If the text box already has an autocomplete list, the old one will be removed.
// Each autocomplete item has a value associated with it; whenever an item is selected, the hidden field generated by the fsn:AutocompleteField will be set to this value.
// Parameters:
//  item: the id (with #) of the text box
//  data: array of hashes containing "text" and "value" fields. Only the "text" field will be displayed in the autocomplete list.
FSN.autocomplete = function(item, data) {
    $(item).unautocomplete(); // Clears the existing autocomplete list (just calling autocomplete() would add new items to the old list)

    var selectFirstValue = $(item).attr("SelectFirst");
    if (selectFirstValue == null || selectFirstValue == "")
        selectFirstValue = false;

    $(item).autocomplete(data, {
        minChars: 0,
        width: 292,
        max: 150,
        matchContains: true,
        autoFill: false,
        selectFirst: selectFirstValue,
        formatItem: function(data, item, total) {
            var tmp = eval("(" + data[0] + ")");
            return tmp.text;
        }
    });
    FSN.setAutocompletionResultFunctionality(item, null);
}

// Some fsn:AutocompleteFields are to be autocompleted based on static values (rather than on lists dynamically loaded from a web service).
// This function sets up autocompletion for the fsn:AutocompleteField with the #-prefixed id given by 'item', 
// based on the contents of the 'options' attribute.
FSN.autocompleteFromOptionsAttribute = function(item) {
    var data = $(item).attr("options").split(";");
    FSN.autocomplete(item, data);
}

$(document).ready(function() {
    // All fsn:AutocompleteFields with the 'autocomplete' class will be given autocomplete functionality
    $(".autocomplete").each(function(index, item) {
        FSN.autocompleteFromOptionsAttribute(item);
    });
    
    if ($(".innringer_dato").length > 0) {
        $(".innringer_dato").datePicker().dpSetStartDate('01/01/2000').trigger('onclick').val(new Date().asString());
    }

    if ($(".dato_felt").length > 0) {
        $(".dato_felt").datePicker({ clickInput: true })
	    .dpSetStartDate('01/01/2000')
	    .trigger('onclick')
	    
	    if($(".til .dato_felt").val() == "")
	        $(".til .dato_felt").val(new Date().format("dd.MM.yyyy")) 

        var idag = new Date()
        var igar = new Date()
        igar.setDate(idag.getDate() - 1)

        if($(".igar").val() == "")
            $(".igar").val(igar.format("dd.MM.yyyy"))
    }

    
});
