﻿/* page.js|customers */
// global vars
var searchOptionText;

// inits script
function initPageJs() {
	// global vars get set on original html
	searchOptionText=$("#mdSearchSelect select option:selected").text();
	autocomplete();
	// inits functions if client is not handheld
	if(!isHandheld()) {
		if($("#mdTranslive").length > 0) transLiveBar();
		if($("#mdLogin").length > 0) {
		    if ($("#mdSearch").length > 0) createSearch();
			//loginBox();
			//accessibleInputs();
			//hideAll();
			//checkboxMarkAll();
			//browserQuirks();
			//autocomplete();
		}
		try {
		  foldInOut();
		  toolTip();
		  setGramArrows();
		} catch (e) {}
	}
}

function autocomplete(){
    $('#headerSearchInput input:eq(0)').ac({
        url : '/Ordbog/layouts/TypeAheadProxy.aspx',
        param : 'q',
        classes : {
            selected : 'selected',
            list : ''
        },
        query : function(input) {
            return '&c=' + $('#mdSearchSelectNewBody li.selected span').attr('class');
        }
    });
}

function transLiveBar(){
	$("#mdTransliveCount").find("h5").text("Den indsatte tekst er").after("<p class=\"counter\">"+ $("#mdTransliveInput textarea").val().length +" tegn</p>");
	$("#mdTranslive").find("textarea").keyup(function(){
		$("#mdTransliveCount .counter").text($(this).val().length + " tegn");
	}).end().find("#mdTransliveInput .mdFormSelectWrap").before("<p>Ryd formularen</p>").end().find("p").click(function(){
		if($.browser.msie){
			$("#mdTransliveInput textarea").html('').focus();
		} else {
			$("#mdTransliveInput textarea").val('').focus();
		}
		$("#mdTransliveCount .counter").text($(this).val().length + " tegn");
	});
	if(!$.browser.safari) $('#mdTranslive textarea').TextAreaResizer();
	$("#mdTranslive textarea").focus();
}

// callback function for Alpha
function ajaxDone(){
	foldInOut();
	toolTip();
	setGramArrows();
}

// fixes some of IE's shortcomings
function browserQuirks(){
	if($.browser.msie&&$.browser.version<=7.0){
		// this fixes an IE bug where li items don't display a bullet unless there is some regular text directly inside
		$(".mdResultItem ul li > ul:first-child").parent().prepend('<div style="visibility:hidden">&nbsp;</div>').css({"margin-bottom":"-22px","padding-bottom":"22px"}).end().find(">li").css({"position":"relative","top":"-22px"});
	}
}

// searchbox is modified and events added & new searchbox is created
function createSearch() {
	$("#mdSearch").addClass("mdSearchJs");
	$("#mdSearchInput label, #mdSearchSelect select, #mdSearchSelect label").hide();
	$("#mdSearchSelect").append('<div id="mdSearchSelectNew"><div id="mdSearchSelectNewHead"></div><ul id="mdSearchSelectNewBody" style="display:none"></ul></div>');
	$("#mdSearchSelect option").each(function(i){
		var sel='';
		if($(this).is(":selected")){sel=' class="selected"'}
		$("#mdSearchSelectNewBody").append('<li'+sel+'><span class="'+$(this).val()+'">'+$(this).text()+'</span></li>');
	});
	
	$("#mdSearchInput input").each(function(){
		// place cursor at end in IE
		if($.browser.msie&&$.browser.version<=7.0){
	 		$(this).bind("focus",function(){
	 			window.o = this;
	 			var r = o.createTextRange();
	 			r.moveStart('character',o.value.length);
	 			r.select();
	 		});
	 	}
		// dont focus on front
		if(!$("body").hasClass("mdSt100")) $(this).focus();
		
		$(this).focus(function(){
			var newVal = "";
			if($(this).val() == searchOptionText){
				newVal ="";
			} else if ($(this).val() == ""){
				newVal = searchOptionText;
			} else {
				newVal = $(this).val();
			}
			$(this).val(newVal);
		});
		
		$(this).blur(function(){
			if($(this).val() == "") $(this).val(searchOptionText);
		})
		
		$(this).dblclick(function(){
			$(this).select();
		})
		 
		if($(this).val() == '') $(this).val(searchOptionText);
	})
	
	
	$("#mdSearchInputHidden input").attr("value",$("#mdSearchSelect select option:selected").val()).attr("name",$("#mdSearchSelect select").remove().attr("name"));
	$("#mdSearchSelectNewHead").html(searchOptionText).click(function(){$("#mdSearchSelectNewBody").slideToggle("fast")});
	$("#mdSearchSelectNewBody li span").click(function(){selectOption($(this).attr("class"))});
	
	$("#mdSearchInput input").keydown(function(e){
		if(e.keyCode==13||e.keyCode==3){
			$("#mdSearch .mdSearchButton").focus().click()
		}
	});
	
	unSelectify($("#mdSearchSelect").get(0));
}

// adds functionality to the loginbox
function loginBox(){
	if(isFrontpage()) {
		$("#mdLogin label").removeClass("mdValueToInput");
	} else {
		if($(".mdLoginError").length > 0){
			$("#mdLoginBody").show();
		}
		$("#mdLoginLink").click(function(){$("#mdLoginBody").show("slow");return false});
	}
}

// hides select & login
function hideAll(){
	$("body").click(function(e){
		if($("#mdSearchSelectNewBody").is(":visible")&&e.target!=$("#mdSearchSelectNewHead").get(0)){$("#mdSearchSelectNewBody").slideUp("fast")}
		if($("#mdLoginBody").is(":visible")&&!isFrontpage()){
			var hide=true;
			$("#mdLoginBody *").each(function(){if(e.target==$(this).get(0)){hide=false}})
			if(hide){$("#mdLoginBody").hide("slow")}
		}
	})
}

// selecting correct dictionary in new searchbox & hides new options afterwards
function selectOption(dicChoice){
	searchOptionText=$("."+dicChoice).text()
	$("#mdSearchSelectNewBody li span").each(function(){
		if($(this).text()==$("#mdSearchInput input").val()){
			$("#mdSearchInput input").val(searchOptionText);
		}
	}).each(function(){
		if($(this).hasClass(dicChoice)){
			$(this).parent().addClass("selected");
			$("#mdSearchSelectNewHead").html(searchOptionText);
			$("#mdSearchInputHidden input").val(dicChoice);
		}else{
			$(this).parent().removeAttr("class");
		}
	});
}

// checks/unchecks all checkboxes
function checkboxMarkAll(){
	$("#mdMarkAll :checkbox").click(function(){
		$("#settings table").find(":checkbox").each(function(){if($("#mdMarkAll :checkbox").is(":checked")){$(this).attr("checked","checked")}else{$(this).attr("checked","")}});
	});
}
	
// folds stuff in/out
function foldInOut(){
    
	$(".mdResultItem:not(.processed) .folded > ul").hide();
	$(".mdResultItem:not(.processed) .foldItem").find("span:first-child").click(function(){$(this).parent().toggleClass("folded").find("ul").slideToggle("fast")}).parents(".mdResultItem").addClass("processed");
	$(".mdResultAlt:not(.processed) .folded div > .mdResultAltSub").hide();
	var dummyHtml;
	$(".mdResultAlt:not(.processed) .foldItem").find(".mdResultAltSub :first-child").each(function(){
		dummyHtml = ($(this).is("li")) ? "<strong>zahid.</strong> " : "";
		//$(this).parents("div").find(">a").after(' <span class="jsline" style="display:none">'+ dummyHtml +$(this).text()+'</span>')
		if( $(this).parents(".folded").find(".jsline").length == 0 )
		{
		    var i=1;
		    var commaSeparatedText = i + '. ' + $(this).html();
		    $(this).nextAll().each(function(){ i++; commaSeparatedText = commaSeparatedText +  i + '. '  + $(this).html(); })
		    //$(this).parents("div").find(">a").after(' <span id="caughtIt" class="jsline" style="display:none">'+ $(this).text()+'</span>')
		    $(this).parents("div").find(">a").after(' <span id="caughtIt" class="jsline" style="display:none">'+ commaSeparatedText+'</span>')		
		    $(this).parents(".folded").find(".jsline").show();
		}
	}).end().each(function(){
		var sourcetitle=$(this).find(".source").attr("title");
		var sourcetext=$(this).find(".source").text();
		if(!$(this).hasClass("folded")){	
			$(this).find(".source").attr("title",sourcetext).text(sourcetitle);
		}else{
			$(this).find(".source").attr("title",sourcetitle).text(sourcetext);
		}
	}).find("a:first").click(function(){
		document.location = $(this).attr("href");
		return false;
	}).end().click(function(e){
		
		if(e.target.href!=$(this).find("a:first").attr("href")){
			$(this).toggleClass("folded").find("div > .mdResultAltSub").slideToggle("fast");
			$(this).find(".jsline").toggle();
			var sourcetitle=$(this).find(".source").attr("title");
			var sourcetext=$(this).find(".source").text();
			if($(this).find(".source").attr("title")==sourcetext){	
				$(this).find(".source").attr("title",sourcetitle).text(sourcetext);
			}else{
				$(this).find(".source").attr("title",sourcetext).text(sourcetitle);
			}
		}
	}).parents(".mdResultAlt").addClass("processed");
}

// makes tooltips in searchresults
function toolTip(){
	$(".mdTooltip:not(.processed)").each(function(){
		if($(this).attr("title")){
			$(this).append('<div class="mdTooltipBox"><p>'+$(this).attr("title")+'</p></div>').removeAttr("title");
			var lPos=this.offsetLeft+this.offsetWidth+3;
			var tPos=this.offsetTop+this.offsetHeight;
			if($.browser.msie&&$.browser.version<=7.0) tPos = tPos + 18;
			$(this).find(".mdTooltipBox").css({"left":lPos,"top":tPos}).end().hover(function(){$(this).find(".mdTooltipBox").show("fast")},function(){$(this).find(".mdTooltipBox").hide("fast")});
		}
	}).addClass("processed");
}

// makes grammer Arrows active
function setGramArrows(){
		$("[id='arrow']:not(.processed)").click(function() {

			if( $(this).attr("class") == "gmfoldItem" )		{
			    $(this).attr("class", "gmfoldItem gmfolded");
			    $(this).next("#gram").fadeOut('fast');
			}
			else {
			    $(this).attr("class", "gmfoldItem")
			    $(this).next("#gram").fadeIn('slow');
			}
            return false;
			}).addClass("processed");
}


// make elements unselectable
function unSelectify(e) {
	if(document.all){
		e.onselectstart=function(){return false}
	} else {
		e.onmousedown=function(){return false}
	}
}

// detects if page is frontpage
function isFrontpage(){
	if($("body").hasClass("mdSt100")){return true}
}

// checks for small screens
function isHandheld() {
	if (screen.availWidth < 600){return true}
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}


//dropDownListDictionaryLanguages

// inits script when dom is ready
$(document).ready(function() {
    initPageJs();
});
/* swfobject.js|customers */
/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype = { useExpressInstall: function (_d) { this.xiSWFPath = !_d ? "expressinstall.swf" : _d; this.setAttribute("useExpressInstall", true); }, setAttribute: function (_e, _f) { this.attributes[_e] = _f; }, getAttribute: function (_10) { return this.attributes[_10]; }, addParam: function (_11, _12) { this.params[_11] = _12; }, getParams: function () { return this.params; }, addVariable: function (_13, _14) { this.variables[_13] = _14; }, getVariable: function (_15) { return this.variables[_15]; }, getVariables: function () { return this.variables; }, getVariablePairs: function () { var _16 = new Array(); var key; var _18 = this.getVariables(); for (key in _18) { _16[_16.length] = key + "=" + _18[key]; } return _16; }, getSWFHTML: function () { var _19 = ""; if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "PlugIn"); this.setAttribute("swf", this.xiSWFPath); } _19 = "<embed type=\"application/x-shockwave-flash\" src=\"" + this.getAttribute("swf") + "\" width=\"" + this.getAttribute("width") + "\" height=\"" + this.getAttribute("height") + "\" style=\"" + this.getAttribute("style") + "\""; _19 += " id=\"" + this.getAttribute("id") + "\" name=\"" + this.getAttribute("id") + "\" "; var _1a = this.getParams(); for (var key in _1a) { _19 += [key] + "=\"" + _1a[key] + "\" "; } var _1c = this.getVariablePairs().join("&"); if (_1c.length > 0) { _19 += "flashvars=\"" + _1c + "\""; } _19 += "/>"; } else { if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "ActiveX"); this.setAttribute("swf", this.xiSWFPath); } _19 = "<object id=\"" + this.getAttribute("id") + "\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\"" + this.getAttribute("width") + "\" height=\"" + this.getAttribute("height") + "\" style=\"" + this.getAttribute("style") + "\">"; _19 += "<param name=\"movie\" value=\"" + this.getAttribute("swf") + "\" />"; var _1d = this.getParams(); for (var key in _1d) { _19 += "<param name=\"" + key + "\" value=\"" + _1d[key] + "\" />"; } var _1f = this.getVariablePairs().join("&"); if (_1f.length > 0) { _19 += "<param name=\"flashvars\" value=\"" + _1f + "\" />"; } _19 += "</object>"; } return _19; }, write: function (_20) { if (this.getAttribute("useExpressInstall")) { var _21 = new deconcept.PlayerVersion([6, 0, 65]); if (this.installedVer.versionIsValid(_21) && !this.installedVer.versionIsValid(this.getAttribute("version"))) { this.setAttribute("doExpressInstall", true); this.addVariable("MMredirectURL", escape(this.getAttribute("xiRedirectUrl"))); document.title = document.title.slice(0, 47) + " - Flash Player Installation"; this.addVariable("MMdoctitle", document.title); } } if (this.skipDetect || this.getAttribute("doExpressInstall") || this.installedVer.versionIsValid(this.getAttribute("version"))) { try { var n = (typeof _20 == "string") ? document.getElementById(_20) : _20; n.innerHTML = this.getSWFHTML(); } catch (e) { } return true; } else { if (this.getAttribute("redirectUrl") != "") { document.location.replace(this.getAttribute("redirectUrl")); } } return false; } }; deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;
/* jquery.ac.js|customers */
/**
 * JSON Autocompleter which autocompletes on a single word in a input type text element.
 * the element used for this plugin MUST only match one element.
 *
 * USAGE:
 * $('#id-of-element').ac({});
 *
 * OPTIONS:
 * - url [The url that is used for autocompletion]
 * - param [The name of the parameter to send with the JSON request]
 * - classes
 *   - selected [is added to the li element when using arrow up or down]
 *   - list [is added to the generated ul list which holds the autocomplete values]
 *
 * @copyright Peytz & Co (www.peytz.dk)
 * @author Henrik Bjørnskov (hb@peytz.dk)
 * @author Troels Knak-Nielsen (tkn@peytz.dk)
 */
$.fn.ac = function(options) {

    var options = $.extend({}, $.fn.ac.defaults, options);
    var element = $(this);
    var timeout = null;
    var self = this;

    var ul = $('<ul />').css({ display: 'none' }).insertAfter(this).attr('id', 'ac-' + $.data(this)).addClass(options.classes.list);

    $('<li class="link"><span>Luk</span></li>').prependTo(ul).find('span').click(function(e) {
        $(this).parent().parent().hide();
        $('li:not(.link)', $(this).parent().parent()).remove();
    });

    element.attr('autocomplete', 'off');

    element.blur(function(e) {
        setTimeout(function() {
            $('li:not(.link)', ul).remove();
            ul.hide();
        }, 200);
    });

    $("#mdSearch .mdSearchButton").click(function(e) {
        var text = $('li.selected', ul).text();
        if (text) {
            element.val(text)
        }
    });

    $('li:not(.link)', ul).live('mousemove', function(e) {
        var elm = $(this);
        var li = $(elm.parent().find('li'));

        $(elm).siblings().removeClass(options.classes.selected);

        $(this).addClass(options.classes.selected);

        $.fn.ac.index = li.index(elm);
    });

    $(this).keyup(
        function(e) {

            var value = options.escape(self.val());




            switch (e.which) {
                case 13: //Enter
                case 27: //Escape
                case 37: //Left
                case 38: //Up
                case 39: //Right
                case 40: //Down
                case 46: //Delete
                    break;
                default:
                    clearTimeout(timeout);

                    $('li:not(.link)', ul).remove()
                    ul.hide();

                    timeout = setTimeout(function() {
                    Dict = $("select[id$='dropDownListDictionaryLanguages'] option:selected").attr("value");
                        
                        $.getJSON(options.url + '?' + options.param + '=' + escape(value) + "&c="+Dict+"&" + getParameterByName("lcode"), function(data) {
                            //                        $.getJSON(options.url + '?' + options.param + '=' + escape(value) + options.query(element), function(data) {
                            $.fn.ac.index = -1;

                            //alert(options.url + '?' + options.param + '=' + escape(value) + options.query(element));

                            ul.find('li:not(.link)').remove();

                            $.each(data.reverse(), function(key, item) {
                                try {
                                    //alert(key + "+"+ item);
                                    var matches = item.match(new RegExp(value, 'i'));
                                    var item = item.replace(new RegExp(value, 'i'), '<strong>' + matches[0] + '</strong>');
                                } catch (e) { }

                                var li = $('<li />').html(item).prependTo(ul).click(function(e) {
                                    $.fn.ac.select(ul, element, $(this).text());
                                    $("#mdSearch .mdSearchButton").focus().click();
                                });
                            });

                            if (ul.find('li:not(.link)').length > 0) {
                                ul.show();
                            }
                        });
                    }, 300);
            }

            e.preventDefault();
        });

    $(this).keydown(
        function(e) {
            var testIndex = $.fn.ac.index;

            switch (e.which) {
                case 13: //Enter
                e.preventDefault();


                    if ($.fn.ac.index != -1) {
                        $.fn.ac.select(ul, element, ul.find('li:eq(' + testIndex + ')').text(), options);
                    }
                    break;
                case 46: //Delete
                case 8: //Backspace
                case 27: //Escape
                    ul.hide();
                    $.fn.ac.index = -1;
                    break;
                case 38: //Up
                    $("input[id$='textBoxSearchInput']").removeAttr("onkeydown");
                    testIndex = $.fn.ac.index - 1;
                    e.preventDefault();
                    break;
                case 40: //Down
                    $("input[id$='textBoxSearchInput']").removeAttr("onkeydown");
                    testIndex = $.fn.ac.index + 1;
                    e.preventDefault();
                    break;
            }
            
            if (e.isDefaultPrevented()) {
                var elm = $('li:eq(' + testIndex + '):not(.link)', ul);

                if (elm.get(0)) {
                    ul.find('li:eq(' + $.fn.ac.index + ')').removeClass(options.classes.selected);
                    $.fn.ac.index = testIndex;
                    elm.addClass(options.classes.selected);
                }
                return false;
            }
            return true;
        });
};

$.fn.ac.index = -1;

$.fn.ac.select = function(ul, element, data) {

    $("input[id$='textBoxSearchInput']").val(data);
    $("input[id$='buttonSearch']").click();
    element.val(data);
    ul.hide();
    $.fn.ac.index = -1;
};

$.fn.ac.defaults = {
    url     : 'ac.json',
    param   : 'p_prefix',
    query   : '',
    escape : function (s) { return unescape(encodeURIComponent(s)); },
    classes : {
        list : 'ac-list',
        selected : 'ac-selected'
    }
};
/* accessibleInputs.js|global */
//Accessible Inputs (requires jQuery)

// moves labels value to inputs if class 'mdValueToInput' is present & then adds focus/blur to inputs
function accessibleInputs(){
	$("label.mdValueToInput[for]").each(function(i){
		// fill input fields with labeltext - html tags
		var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
		var newVal = this.innerHTML.replace(regexp,"");
		//if el is type=input or textarea
		if($("#"+this.htmlFor).is("input") || $("#"+this.htmlFor).is("textarea")){
			if(($("#"+this.htmlFor).val() == "") || ($("#"+this.htmlFor).val() == newVal)){
				$("#"+this.htmlFor).attr("value",newVal);
			}
			// create onclick/blur functionality
			$("#"+this.htmlFor).focus(function(){if(this.value == newVal) this.value = "";});
			$("#"+this.htmlFor).blur(function(){if(this.value == "") this.value = newVal;});
		// if el is select	
		} else if($("#"+this.htmlFor).is("select")){
			var orgOptions = $("#"+this.htmlFor).html();
			var newOptions = '<option value="">'+newVal+'</option>'+orgOptions;
			// IE special Kung Fu
			if($.browser.msie && $.browser.version < 8){
				var go=0;
				$("#"+this.htmlFor).find("option").each(function(i){
					if($(this).get(0).defaultSelected){
						go=1;
					}
				})
				if(go==0){
					newOptions = newOptions.replace(/selected>/g,">");
				}
			}
			$("#"+this.htmlFor).html(newOptions);
			// IE8 force choose first option
			if($.browser.msie && $.browser.version <= 8){
				$("#"+this.htmlFor + " option:first").attr("selected","selected")
			}
		}
		// hide label
		$(this).hide();
	})
	cleanForms();
}

// makes sure that label values are not submitted to forms
function cleanForms(){
	$("form:has(label.mdValueToInput)").submit(function(){
		$("label.mdValueToInput[for]").each(function(){
			// check if value is same as label
			var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
			var newVal = this.innerHTML.replace(regexp,"");
			if($("#"+this.htmlFor).attr("value") == newVal){
				$("#"+this.htmlFor).attr("value","");
			}
		})
	})
}

/* textarearesizer.js|customers */
(function($){
	var textarea,staticOffset;
	var iLastMousePos=0;
	var iMin=32;
	var grip;
	$.fn.TextAreaResizer=function(){
		return this.each(function(){
			textarea=$(this).addClass('processed'),staticOffset=null;
			$(this).wrap('<div class="resizable-textarea"><span></span></div>').parent().append($('<div class="grippie"></div>').bind("mousedown",{el:this},startDrag));
			var grippie=$('div.grippie',$(this).parent())[0];
			grippie.style.marginRight=(grippie.offsetWidth-$(this)[0].offsetWidth)+'px'
		})
	};
	function startDrag(e){
		if($.browser.msie) $("#flashcontent").css("visibility","hidden");
		textarea=$(e.data.el);
		textarea.blur();
		iLastMousePos=mousePosition(e).y;
		staticOffset=textarea.height()-iLastMousePos;
		textarea.css('opacity',1.00);
		$(document).mousemove(performDrag).mouseup(endDrag);
		return false
	}
	function performDrag(e){
		var iThisMousePos=mousePosition(e).y;
		var iMousePos=staticOffset+iThisMousePos;
		if(iLastMousePos>=(iThisMousePos)){
			iMousePos-=5
		}
		iLastMousePos=iThisMousePos;
		iMousePos=Math.max(iMin,iMousePos);
		textarea.height(iMousePos+'px');
		if(iMousePos<iMin){
			endDrag(e)
		}
		return false
	}
	function endDrag(e){
		if($.browser.msie) $("#flashcontent").css("visibility","visible");
		$(document).unbind('mousemove',performDrag).unbind('mouseup',endDrag);
		textarea.css('opacity',1);
		textarea.focus();
		textarea=null;
		staticOffset=null;iLastMousePos=0
	}
	function mousePosition(e){
		return{
			x:e.clientX+document.documentElement.scrollLeft,y:e.clientY+document.documentElement.scrollTop
		}
	}
})(jQuery);

