
// LOAD-ORDER: 110

/*
*  bla bla
*
**/
var locationHref = location.href.replace(/#/g,'');

var popupPdfEventListener = {	
	
	onOverlayHide: function() {		
		toggleAnimation();
	}
	
};

function pdfLinkClicked() {
	if($('links')){
		popupPdf(getHashArrayFromHTMLDOM($$('.endpoint, .coll-in-mdd')));
	}
	else{
		grabFromServer( getCurrentLocationXMLRepUrl() );  /* async event */
	}
}

function getHashArrayFromHTMLDOM(elements){
	return elements.collect(function(element) {
		return {href:element.down('a').getAttribute('href'),title:element.down('a').innerHTML.stripTags()};
	});
	
}

function getHashArrayFromXMLDOM(doc){
	var elements = 	doc.firstChild.childNodes;
	var hashArray = [];
	for(i = 0; i < elements.length; i++){
		if(elements[i].tagName == 'dw:coll-in-mdd'){
			var nameTagArray = elements[i].getElementsByTagName('dw:name');
			if(nameTagArray.length > 0){
				hashArray.push( {href:elements[i].getAttribute('href'),title:elements[i].getElementsByTagName('dw:name')[0].firstChild.nodeValue} );
			}
			else{
				hashArray.push( {href:elements[i].getAttribute('href'),title:elements[i].getElementsByTagName('name')[0].firstChild.nodeValue} )
			}
		}
	}
	return hashArray;
}

function grabFromServer(url){
	new Ajax.Request(url, {
						  method: 'get',
						  onFailure: function(){ alert("Ajax-Error"); } ,
						  onSuccess: function(transport) {
											  	document.myXMLDOM = transport.responseXML;
											    popupPdf(getHashArrayFromXMLDOM(transport.responseXML));
											  }
					});
}

function getCurrentLocationXMLRepUrl(){
	var locationHref = location.href.replace(/#/g,'');
	
	if(locationHref.indexOf('?') > 0) {
		locationHref += "&rep=xml";
	} else {
		locationHref += "?rep=xml";
	}
	
	return locationHref;
}

function popupPdf(hashList){
	/*
	Todo:
	1. hent referanse til eller opprett div med id 'popupPdf' (Kap 3/7)
		b. opprette en knapp med eventlistener som kaller funksjon 'popupPdfSubmit' og en knapp 'avbryt' (Kap 6)
	2. populer div'en med evt checkboxer. hentes r�tt fra ul'en 'links' (Kap 7)
	3. animere frem div'en
	
	*/
	
	if(hashList.length > 1){

		if(!$('pdfForm')){
			var div = $(document.createElement('div'));				
			div.writeAttribute('id', 'pdfForm');
			div.addClassName( 'foxed');
			div.setStyle( { 'display':'none'  } ); //makes effect possible!
			
			var html_content = "<h1>" + I18N['page.control.download'] + "</h1><form>";
			html_content += "<h4>" + I18N['pdf.choose'] + ": <a href='#' id='all'>" + I18N['pdf.all'] + "</a>, <a href='#' id='none'>" + I18N['pdf.none'] + "</a></h4><form>";

			hashList.each(function(item, index){
				html_content += "<input type='checkbox' value='" + item['href'] + "' id='pdf" + index + "' checked='true'/>" + item['title'] + "<br/>\n";
				});

			html_content += "<input type='submit' name='pdfSubmit' id='pdfSubmit' value='" + I18N['pdf.submit.value'] + "'/>";
			html_content += "<input type='button' name='pdfClose' id='pdfClose' value='" + I18N['pdf.cancel.value'] + "'>";
			html_content += "<a href='#' class='close'><span>close</span></a>";
			html_content += "</form>"
			div.update(html_content);
			Element.insert( $$('body')[0], { 'bottom' : div } );
			var form = $('pdfForm').down('form');
			form.stopObserving('submit', null);
			form.observe('submit', function(event){
				popupPdfSubmit();
				event.preventDefault();});
			$('pdfClose').observe('click',toggleAnimation);
			$$('#pdfForm .close')[0].observe('click',toggleAnimation);
			$('all').observe('click', selectAll);
			$('none').observe('click', deselectAll);
			
			toggleAnimation( );
	
		}
		else{
			toggleAnimation( );
		}
	}
	else{
		//newPdfWindow(locationHref.substring(0,locationHref.lastIndexOf('?')) + '.pdf' + locationHref.substring(locationHref.lastIndexOf('?')));
		newPdfWindow(locationHref + "&rep=pdf");
	}
}



function toggleAnimation( ){
		
		if($('pdfForm').visible()){
				$('pdfForm').hide();
				Overlay.hideOverlay();
			}
			else{
				Overlay.showOverlay( popupPdfEventListener );
				Effect.Appear($('pdfForm'));
			}
			
}



function popupPdfSubmit(){
	/*
	Todo:
	1. loope alle checkboxer og hente href'ene inn i Array (Kap 3)
	2. exclude_children = Array.join(',')  
	3. Href = Href + exclude_children
	4. location = Href
	*/

	var chkbx = $$('#pdfForm input[type="checkbox"]:not(:checked)');
	var excl_children = "";
	var location = locationHref;
	
	
	chkbx.each(function(item, index){
		if(index < chkbx.length-1){
			excl_children += escapeUrl(item.readAttribute('value')) + ",";
		}
		else{
			excl_children += escapeUrl(item.readAttribute('value')) ;
		}
	});
	if(location.indexOf('?') > 0){
		location += '&excl_children=' + excl_children ;
	}
	else{
		location += '?excl_children=' + excl_children;
	}
	location += "&rep=pdf";
	
	toggleAnimation();
	newPdfWindow(location);
	//location.href=locationHref;
}

function escapeUrl(unescapedString){
	unescapedString = unescapedString.replace(/\?/g, '%3F');
	unescapedString = unescapedString.replace(/&/g, '%26');
	return unescapedString;
}

function newPdfWindow(url){
	//alert(url);
	window.open(url, "Print", "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=yes, width=800, height=600");
}

function selectAll(){
	
	var chkbx = $$('#pdfForm input[type="checkbox"]:not(:checked)');
	chkbx.each(function(item, index){
		item.checked = true;
	});

}

function deselectAll(){
	var chkbx = $$('#pdfForm input[type="checkbox"]::checked');
	chkbx.each(function(item, index){
		item.checked = false;
	});

}

function moreThanOneNode(){
	
	return true;  /* pls impl */
}


document.observe('dom:loaded' , function() {

	/* magic! */
	/*
	Todo:
	
	1. grab pdf <a href (Kap 3)
	2. sette opp en eventListener p� onclick som kaller funksjon som heter popupPdf (Kap 6)
	3. sette # i href	(Kap 3/7)
	*/

	if( $('pdf') ){
				
				$('pdf').observe('click', pdfLinkClicked );
				$('pdf').writeAttribute('href','#');
	}
	
})
