﻿var parseUri = {
	options: {
		strictMode: true,
		key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
		q:   {
			name:   "queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},
		parser: {
			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
			loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
		}
	},
	parseUri: function(value) {
		var	o   = parseUri.options,
			m   = o.parser[o.strictMode ? "strict" : "loose"].exec(value),
			uri = {},
			i   = 14;
		while(i--) {
			uri[o.key[i]] = m[i] || "";
		}
		uri[o.q.name] = {};
		uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
			if($1) {
				uri[o.q.name][$1] = $2;
			}
		});
		return uri;
	}
};

jQuery.fn.addDatePicker = function(){
   $(this).datePicker().val(new Date().asString()).trigger('change');
};
jQuery.fn.initMenu = function(){
   $(this).find("ul").not("ul.selected").each(function(){
       $(this).addClass("closed"); 
   });
};
jQuery.fn.adminMenu = function(){
   
   $(this).find(".has-more").each(function(){
        var ul = $(this).children("ul");
        $(this).click(function(){
            ul.toggleClass("closed",1000);
            //return false;
        });
   });
};
jQuery.fn.activityMenu = function(){
   $(this).find(".has-more").each(function(){
        var ul = $(this).next("ul");
        $(this).click(function(){
            ul.toggleClass("closed",1000);
            return false;
        });
   });
};

jQuery.fn.handleComments = function(){
	if(this.length > 0){
		$(this).each(function(){
			var cont = $(this).parent(),
			cHeader = $(this).clone(),
			cControls = cont.parent().find("ul.comment-controls"),
			cTextbox = cont.find("textarea");
			
			cont.toggle();
			
			if(cControls.length > 0){
				cControls.append($("<li>").append(cHeader));
			}else{
				cControls = $("<ul>").addClass("comment-controls");
				cControls.append($("<li>").append(cHeader));
				cControls.insertBefore(cont);
			}
			
			if(cont.hasClass("has-Comment")){
				cHeader.addClass("has-comment")
			}
			if(cont.hasClass("has-Deviation")){
				cHeader.addClass("has-deviation")
			}
			
			cHeader.click(function(){
				if(!cTextbox.hasClass("tinymce")){
					cTextbox.tinymce({
						// Location of TinyMCE script
						script_url : '/PageUI/Js/tiny_mce/tiny_mce.js',

						// General options
						theme : "advanced",
						plugins : "",
						
						width : "420",

						// Theme options
						theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,link,unlink",
						theme_advanced_buttons2 : "",
						theme_advanced_buttons3 : "",
						theme_advanced_buttons : "",
						theme_advanced_toolbar_location : "top",
						theme_advanced_toolbar_align : "left",
						theme_advanced_statusbar_location : "bottom",
						theme_advanced_resizing : false

					});
					cTextbox.addClass("tinymce");
				}
				cont.toggle();
			});
		
		});
	}
};

$.dpText = {
	TEXT_PREV_YEAR		:	'Föregående år',
	TEXT_PREV_MONTH		:	'Föregående månad',
	TEXT_NEXT_YEAR		:	'Nästa år',
	TEXT_NEXT_MONTH		:	'Nästa månad',
	TEXT_CLOSE			:	'Stäng',
	TEXT_CHOOSE_DATE	:	'Välj datum'
} 

var dataFromSelect = function(jqSelectElm){
    var arr = [];
    jqSelectElm.find("option").each(function(){
        var row = {id:$(this).attr("value"), name:$(this).text()};
        arr.push(row);
    
    });
    return arr;
    
};

var definitionHandler={
    init: function(){
        $("a.definition").each(function(){
            $(this).click(function(){
                var href = $(this).attr("href");
                var mess = $(document.createElement("div"));
                mess.append($.ajax({
                    url: href,
                    async: false
                    }).responseText);

                return false;
            })
        });
    },
    definition: function(anc){
        var definition = "test";
        
        return definition;
    }
};

var statuteLoadMessage = "<p class='load-message'>Vänligen vänta medan Regelrätt uppdaterar Er författningslista - detta kan ta upp till 20 sekunder</p>"
var reportLoadMessage = "<p class='load-message'>Vänligen vänta medan Regelrätt skapar Er rapport - detta kan ta upp till 1 minut</p>"
var searchLoadMessage = "<p class='load-message'>Vänligen vänta medan sökning sker i Regelrätt</p>"

jQuery.fn.handleLinks = function(){
	$(this).find("a").each(function(){
		if(this.childNodes.length > 0 && 
			(this.childNodes[this.childNodes.length - 1].nodeType == 3 ||
			this.childNodes[this.childNodes.length - 1].nodeType == 8 ||
			(this.childNodes[this.childNodes.length - 1].nodeType == 1 && this.childNodes[this.childNodes.length - 1].tagName != "IMG"))) {
			var href = $(this).attr("href");
			if(href) {
				var hrefHost = parseUri.parseUri(href).host;
				if(hrefHost !== "" && hrefHost != document.location.hostname && hrefHost != "www." + document.location.hostname && hrefHost != document.location.hostname.replace("www.", "")) {
					$(this).addClass("external");
					$(this).attr("rel", "external");
					$(this).attr("target", "_blank");
					$(this).attr("title", 'Öppnas i nytt fönster ' + href);
				}
			} else {
				$(this).addClass("no-href");
			}
		} else {
			$(this).addClass("not-text");
		}
	});
	return this;
};

$(document).ready(function() {
    $(".date-pick").addDatePicker();
    $("#activity-menu ul:not(.edit-mode)").activityMenu();
    $("#admin-navigation").adminMenu();
    $("#side-bar #activity-menu ul:not(.edit-mode)").initMenu();
    $("#admin-navigation").initMenu();
    

	$("div.paragraph-options").each(function(){
		var parent = $(this).parent();
		$(this).hover(
			function(){
				parent.toggleClass("highlited");
			},
			function(){
				parent.toggleClass("highlited");
			}
		)
	});


    $("#primary #toc").toc({ exclude: 'h1, h2, h3, h5, h6, h4:first' });
    


    var definitionData = function(data) {
                        data = $(data).find('#DefinitionContent');
                        return data;
                        };
	var instructionsData = function(data) {
                        data = $(data).find('body');
                        return data;
                        };

	$('.sanction-level img').cluetip({arrows: true, splitTitle: '|'});
	$('a.definition').cluetip({activation: 'click', sticky: true, closePosition: 'title', arrows: true, ajaxProcess: definitionData, closeText: "Stäng"});
	//$('#system-instructions').cluetip({activation: 'click', sticky: true, closePosition: 'title', arrows: true, closeText: "Stäng", width:720});

    $('#ac').click(function() {
        $.blockUI({ message: $('#t1') });

        $('#btn').click(function() {
            $.unblockUI();
            return false;
        });
    });

    $("#acGroup").autocomplete(dataFromSelect($("select.allGroups")), {
        minChars: 0,
        width: 500,
        matchContains: "word",
        autoFill: false,
        formatItem: function(row, i, max) {
            return i + "/" + max + ": \"" + row.name + "\" [" + row.id + "]";
        },
        formatMatch: function(row, i, max) {
            return row.name + " " + row.id;
        },
        formatResult: function(row) {
            return row.name;
        }
    }).result(function(event, data, formatted) {
        if (data) {
            $(this).parent().next().find("select").val(data.name);
        }
    });

    $("#acParagraph").autocomplete(dataFromSelect($("select.allParagraphs")), {
        minChars: 0,
        width: 500,
        matchContains: "word",
        autoFill: false,
        formatItem: function(row, i, max) {
            return i + "/" + max + ": \"" + row.name + "\" [" + row.id + "]";
        },
        formatMatch: function(row, i, max) {
            return row.name + " " + row.id;
        },
        formatResult: function(row) {
            return row.name;
        }
    }).result(function(event, data, formatted) {
        if (data) {
            $(this).parent().next().find("select").val(data.name);
        }
    });

    
    
    $(".activity h5.comment").not($(".report .activity h5.comment")).handleComments();
    	
    $("div.group-options ul").toggle();
    
    $("div.group-options h5").click(function(){
		$(this).next("ul").toggle();
		$(this).parent().toggleClass("open");
	});
	
	$("div.paragraph-options ul").toggle();
    $("div.paragraph-options h5").click(function(){
		$(this).next("ul").toggle();
		$(this).parent().toggleClass("open");
	});
	
	
	$(".statutes .statute-comment, .statutes .statute-desc, .statute .statute-links").toggle();

	$(".more").click(function(){
		$(this).toggleClass("panel-open");
		$(this).next("ul:first").toggle();
		return false;
    });

	$(".statutes a.view-desc, .statutes a.more-activities, .statutes a.view-comment").click(function(){
		$(this).toggleClass("panel-open");
		$(this).next("div").toggle();
		return false;
	});  
	
	$("ul.statutes").toggle();
	
	$("#show-all-activities").click(function(){
		$("ul.statutes").toggle();
		$("a.more").toggleClass("more-open");
		return false;
    });
    
    $('#activity-menu ul li a.statutes').click(function() { 
        $.blockUI({ message: statuteLoadMessage, css: { width: '350px' } }); 
    });
    $('#reports').click(function() { 
        $.blockUI({ message: reportLoadMessage, css: { width: '350px' } }); 
    }); 
    $('input.SearchButton').click(function() { 
        $.blockUI({ message: searchLoadMessage, css: { width: '350px' } }); 
    }); 
    
    $("#main-content").handleLinks();
    
    $('.edit-definition textarea.tinymce,.edit-statute textarea.tinymce,.edit-paragraph textarea.tinymce').tinymce({
			// Location of TinyMCE script
			script_url : '/PageUI/Js/tiny_mce/tiny_mce.js',

			// General options
			theme : "advanced",
			plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

			// Theme options
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,cleanup,code,|,preview",
			theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,|,fullscreen",
			theme_advanced_buttons4 : "cite,abbr,acronym,del,ins",
			theme_advanced_blockformats : "p,div,blockquote",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true

		});
		
		$('.edit-helplet textarea.tinymce, .edit-news textarea.tinymce, .edit-calendar-event textarea.tinymce').tinymce({
			// Location of TinyMCE script
			script_url : '/PageUI/Js/tiny_mce/tiny_mce.js',

			// General options
			theme : "advanced",
			plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

			// Theme options
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,cut,copy,paste,pastetext,pasteword,|,bullist,numlist,|,link,unlink,cleanup",
			theme_advanced_buttons2 : "",
			theme_advanced_buttons3 : "",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true

		});

});
