var urlHandler={
	addQueryKeyValue: function(url,queryKey,value) {
		var urlWithoutHash=urlHandler.stripHash(url),
					hash=urlHandler.getHash(url);
		return urlWithoutHash+(urlWithoutHash.indexOf("?")> -1?"&":"?")+queryKey+"="+encodeURIComponent(value)+(hash===null?"":"#"+hash);
	},
	removeQueryKey: function(url,queryKey) {
		var m=new RegExp("(\\?|&)("+queryKey+"=.*?)($|&|#)").exec(url);
		return m===null?url:url.replace(m[1]+m[2]+m[3],m[1]=="?"&&m[3]!==""?m[1]:m[3]);
	},
	hasQueryKey: function(url,queryKey) {
		return url.indexOf("&"+queryKey+"=")> -1||url.indexOf("?"+queryKey+"=")> -1;
	},
	getValueForQueryKey: function(url,queryKey) {
		var m=new RegExp("(\\?|&)"+queryKey+"=(.*?)($|&|#)").exec(url);
		return m===null?null:decodeURIComponent(m[2]).replace(/[\+]/g," ");
	},
	getValueForQueryKeyInHash: function(url,queryKey) {
		var m=new RegExp("[#](.*?&){0,1}?"+queryKey+"=(.*?)($|&)").exec(url);
		return m===null?null:decodeURIComponent(m[2]).replace(/[\+]/g," ");
	},
	replaceOrAddQueryKeyAndValue: function(url,queryKey,value) {
		var queryValue=urlHandler.getValueForQueryKey(url,queryKey),
					newUrl,
					urlWithoutHash,
					hash;
		if(queryValue==value) {
			return url;
		}
		newUrl=url.replace(new RegExp("(\\?|&)("+queryKey+"=)(.*?)($|&|#)"),"$1$2"+encodeURIComponent(value)+"$4");
		if(url==newUrl) {
			urlWithoutHash=urlHandler.stripHash(url);
			hash=urlHandler.getHash(url);
			newUrl=urlWithoutHash+(urlWithoutHash.indexOf("?")> -1?"&":"?")+queryKey+"="+encodeURIComponent(value)+(hash===null?"":"#"+hash);
		}
		return newUrl;
	},
	stripQuery: function(url) {
		var hash=urlHandler.getHash(url);
		return url.indexOf("?")> -1?url.substring(0,url.indexOf("?"))+(hash===null?"":"#"+hash):url;
	},
	stripHash: function(url) {
		return url.indexOf("#")> -1?url.substring(0,url.indexOf("#")):url;
	},
	getHash: function(url) {
		var m=/#(.*?)$/.exec(url);
		return m===null?null:m[1];
	}
}


var nextSib;

var newwindow;

function displayParkingSpace(request, id, address, type, width, height, scale)
{
	var param = '?Request='+request+'&ID='+id+'&Type='+type+'&Width='+width;
	param = param+'&Height='+height+'&Scale='+scale+'&Address='+address;
	document.getElementById('mapFrame').src = 'http://gi.wspgroup.se/shemparkeringswebb/MapPage.aspx'+param;
}

function ToggleDiv(DivName) { 
    with (document.getElementById(DivName).style) { 
        if (display == "none") {
            display = "";
        } else {
            display = "none"; 
        }
    }
}

function poptastic(url)
{
	var newwindow=window.open(url,'name','resize','height=480,width=640');
	if (newwindow) newwindow.focus();
}

function popnewwindow(url,name,params)
{
	var newwindow=window.open(url,name,params);
	if (newwindow) newwindow.focus();
}

function popApartment(img, address){
  var generator=window.open('','apartmentImage','height=640,width=820,menubar=yes');   
  
  generator.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\n');
  generator.document.write('"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n');
  generator.document.write('<html lang="sv" style=\"overflow:hidden;\">\n<head>\n<title>' + address + '</title>\n');
  generator.document.write('<link rel="stylesheet" type="text/css" media="screen" href="/PageUI/Styles/default.css">\n');
  generator.document.write('</head>\n<body>\n');
  generator.document.write('<br/>\n');    
  generator.document.write("<div style=\"margin:0 10px;\"><img src='" + img + "' alt='" + address + "'/>\n");
  generator.document.write('<p style=\"margin-top:3px;\">' + address + '<a style=\"position:absolute;right:10px;\" href="#" onclick=\"window.close()\"> St&auml;ng detta f&ouml;nster</a></p></div>\n');
  generator.document.write('<br/>\n');  
  generator.document.write('</body>\n</html>');
  generator.document.close();
  if (generator) generator.focus();
}

function closeInfoBox(obj)
{
	nextSib.className = "popup-module";
	nextSib.style.visibility = "hidden";
	return false;
}

function showInfoBox(obj)
{		
	if(nextSib)
		nextSib.style.visibility = "hidden";
		
	
	
	// Find next sibling
	nextSib = obj.nextSibling;
	while(nextSib.nodeName != "DIV" && nextSib.nextSibling != undefined)
	{
		nextSib = nextSib.nextSibling;		
	}
	
	// position object		
	//var x = obj.offsetLeft;
	//var y = obj.offsetTop;
	
	//var alignObj = obj;
	//var tempObj = alignObj;
	
	/*while (tempObj.offsetParent.tagName != "BODY"){
		x += tempObj.offsetLeft;
		y += tempObj.offsetTop;
		tempObj = tempObj.offsetParent;			
	}
	
	x += tempObj.offsetLeft;
	y += tempObj.offsetTop;*/
					
	nextSib.className = "popup-module-active";
					
	//nextSib.style.left = (x - 20) + "px";
	
	//nextSib.style.top = (y + 25) + "px";
	nextSib.style.visibility = "visible";
	
	return false;
}

function clearInputField(field, value)
{
	if(field.value == value)
		field.value = "";	
}


function getElementByPartialId(strPartialId, tagName)
{
	if(typeof strPartialId != "string") 
		return null;
	var tagName = tagName || "*";
	var coll = document.getElementsByTagName(tagName);
	for(i=0; i<coll.length; i++)
	{
		if(coll[i].id.indexOf(strPartialId) > -1)	
			return coll[i];
	}
	return null;
}

function getElementsByPartialId(strPartialId, tagName)
{
	var ary = [];
	if(typeof strPartialId != "string") 
		return ary;
	var items = 0;	
	var tagName = tagName || "*";
	var coll = document.getElementsByTagName(tagName);
	for(i=0; i<coll.length; i++)
	{
		if(coll[i].id.indexOf(strPartialId) > -1)
		{
			ary[items] = coll[i];
			items++;
		}
	}
	return ary;
}

$(document).ready( function() {
    $('A[rel="external"]').click( function() {
        window.open( $(this).attr('href') );
        return false;
    });
    TextDocumentLinksRemoveTranslation();
    RemoveGoogleTranslationSourceTextForMainHeader();
    InitInvoiceTable();
    
    if ($.browser.msie && $.browser.version.substr(0,1)<8) {
		AddWidthOnFloatedButtonContainers();
	}
    
    $("input.merBeskrivning").focus(function () {
         $(".beskrivandeText").addClass("selected");
    });

});

function InitInvoiceTable() {
    $('#invoices .select').click(function() {
        url = $(this).attr('href');
        url += "&json=1";
        invoiceId = urlHandler.getValueForQueryKey(url, "invoiceId");
        if ($("#invoices #invoiceDetails_" + invoiceId + " .populated").length > 0) {
            SlideInvoiceDetails(invoiceId);
        } else {
            tbody = $("#invoices #invoiceDetails_" + invoiceId + " tbody");
            tbody.addClass("populated");
            $.getJSON(url, function(data) {
                var previousContractNumber = '';
                for (var i = 0; i < data.length; i++) {
                    tr = $(document.createElement('tr'));

                    sum = $(document.createElement('td'));
                    sum.text(data[i].FormatedSum);
                    sum.addClass("subSumColumn");
                    sum.prependTo(tr);

                    contractNumber = $(document.createElement('td'));
                    if (i == (data.length-1) || data[i].ContractNumber != data[i + 1].ContractNumber) {
                        contractNumber.text(data[i].ContractNumber);
                    }
                    contractNumber.addClass("contractNumberColumn");
                    contractNumber.prependTo(tr);

                    desc = $(document.createElement('td'));
                    desc.text(data[i].Description);
                    desc.addClass("descriptionColumn");
                    desc.prependTo(tr);

                    tr.prependTo(tbody);
                    previousContractNumber = data[i].ContractNumber;
                }
                SlideInvoiceDetails(invoiceId);
            });
        }
        return false;
    });	
}

function SlideInvoiceDetails(invoice_Id){
	$("#invoices #invoiceDetails_" + invoice_Id + " div").slideToggle(100);
	$("#invoices #invoice_" + invoice_Id).toggleClass("maximized");
}

function AddWidthOnFloatedButtonContainers(){
	var width;
	jQuery.each($('.submitButtonContainer'), function() {
		width = 0;
		jQuery.each($(this).children('button'), function() {
			width = width + $(this).width();
		});
		$(this).width(width+20);
    });
}


//Fix so google translate doen´t translate linked documents
function TextDocumentLinksRemoveTranslation() {
	var regExp = new RegExp('http://.*/translate_c?.*u=(.*.(pdf|txt|doc|xls|docx))&.*');
	jQuery.each($('#content-area a'), function() {
		var href = $(this).attr('href');
		var match = regExp.exec(href);
		if (match != null) {
			$(this).attr('href', match[1]);
		}
    });
}

function RemoveGoogleTranslationSourceTextForMainHeader() {
	$("h1 .google-src-text").replaceWith("");
}

function AddPrintLink(printLabel) {
	$(document).ready( function() {
		$("div#printLinkWrapper").replaceWith('<a href="#" class="errorReportPrintLink" onClick="window.print();return false;">' + printLabel + '</a>');
	});
}