//alert('loaded');
var intSelectionLength=0;

function downloadManagerGenerate(){
	//alert('will generate the download based on the user selection');
	var strIdMatch='';
	var bolCapture=true;
	var arrPageNumbers=[];
	var arrIndexItems=[];
	//for ie (otherwise tr would have been used)
	var arrLinks=objPageElements.elcontent.getElements("div#far-download_mngr_selection table td.far-left a")
	//alert(arrRows.length)
	
	if(arguments.length>0){
		strIdMatch=arguments[0];		
	}
	
	arrLinks.each(function(elLink, index){
		var elRow=elLink.getParent('tr');
		//alert(elRow.get('html'));
		if($defined(elRow.getElement('td.far-left a'))){
			var strUid=elRow.get('uid');
			//alert(strUid);
			if(strIdMatch.length>0){
				if(strUid==strIdMatch){
					bolCapture=true;
				}else{
					bolCapture=false;
				};
			}else{
				bolCapture=true;
			}
			
			if(bolCapture){
				var strPages=elRow.get('title');
				var strTitle=elRow.getElement('td.far-left a').get('text');
				arrIndexItems.include(strTitle);
				
				var arrPages=strPages.split('-');
				var intStart=arrPages[0].toInt();
				var intEnd=arrPages[1].toInt();
				var i;
				for (i=intStart;i<=intEnd;i++){
					arrPageNumbers.include(i);
				}
			}
		}		
	});
	

	
	//alert('* '+arrPageNumbers.join(',')+" - "+arrIndexItems.join(','));
	
	downloadManagerGenerateStart(arrIndexItems.join('|'), arrPageNumbers.join('|'));
}


function downloadManagerRemoveFromSelectionAll(){
	//alert('removes all the downloads from the selection');
	var hashDownloadManagerPages=new Hash.Cookie('downloadmanager', {duration: 3600, path: '/'});
	hashDownloadManagerPages.empty();

	var elDiv=objPageElements.elcontent.getElement("div#far-download_mngr_selection td.far-remove_all a")
	elDiv.addClass('busy');
	(function(){
		downloadManagerUpdateSelection();
		
		//remove all the selected classes from the bottom panel
		var arrDiv=objPageElements.elcontent.getElements("div#far-download_mngr_section_downloads td.far-right div");
		//alert(arrDiv.length);
		arrDiv.each(function(elDiv, index){
			var strClassName=elDiv.get('class');
			if(strClassName=='far-remove')elDiv.setStyle('display','none');
			if(strClassName=='far-add')elDiv.setStyle('display','inline');
		})
		
	}).delay(950);		
}

function downloadManagerRemoveFromSelection(strId, strType){
	//alert('removes item '+strId+' from the selection');
	var elRow, elDiv;
	var strPageNumbers;
	
	//use the page numbers as a unique rerefernce to work with
	if(strType=="fixed"){
		elRow=objPageElements.elcontent.getElement("div#far-download_mngr_section_downloads tr[pdf="+strId+"]");
		strPageNumbers=elRow.get('title');
	}else{
		//for ie (otherwise tr would have been used)
		var arrLinks=objPageElements.elcontent.getElements("div#far-download_mngr_selection table td.far-left a")
		
		arrLinks.each(function(elLink, index){
			var elRowNested=elLink.getParent('tr');
			//alert(elRow.get('html'));
			if($defined(elRowNested.getElement('td.far-left a'))){
				var strUid=elRowNested.get('uid');
				if(strId==strUid){
					elRow=elRowNested;
					//alert('found');
				}
			}		
		});		
		
		//elRow=objPageElements.elcontent.getElement("div#far-download_mngr_selection tr[uid="+strId+"]")
		strPageNumbers=elRow.get('title');
	}
	
	var hashDownloadManagerPages=new Hash.Cookie('downloadmanager', {duration: 3600, path: '/'});
	if(hashDownloadManagerPages.hasValue(strPageNumbers)){
		strKey=hashDownloadManagerPages.keyOf(strPageNumbers); 
		hashDownloadManagerPages.erase(strKey);
	}	

	//start animating
	var elDiv
	switch(strType){
		case "fixed":
			elDiv=elRow.getElement("td.far-right div.far-remove")
			break;
		case "selection":
			elDiv=elRow.getElement("td.far-right div.far-remove")
			break;
		case "selection_duplicate":
			elDiv=elRow.getElement("td.far-right div.far-duplicate")
			break;			
		
	}
	elDiv.addClass('busy');

	statsStorePageEvent({eventname: 'download_remove', value1: strPageIdSystem, value2: getCssSelector(elDiv)});
	
	if(strType=="fixed"){
		(function(){
			elDiv.setStyle('display','none');
			elDiv.getParent().getElement('.far-add').setStyle('display','inline');		
			elDiv.removeClass('busy')
		}).delay(1000);
	}else{
		//action was executed from the selection list - now invert the selected "v" in the fixed list
		var elRowFixed=objPageElements.elcontent.getElement("div#far-download_mngr_section_downloads tr[title="+strPageNumbers+"]");
		if($defined(elRowFixed)){
			(function(){
				var elDiv=elRowFixed.getElement('div.far-remove');
				if($defined(elDiv)){
					elDiv.setStyle('display','none');
					elDiv.getParent().getElement('.far-add').setStyle('display','inline');
				}
			}).delay(1000);			
			
		}
	}

	(function(){
		downloadManagerUpdateSelection();
	}).delay(950);	
	
}

function downloadManagerAddToSelection(strId){
	//alert('adds download item '+strId+' to the selection');
	
	var elRow=objPageElements.elcontent.getElement("div#far-download_mngr_section_downloads tr[pdf="+strId+"]")
	var strPageNumbers=elRow.get('title')
	//alert(strPageNumbers)
	
	//safety - check if this one is already in the selection
	var elRowSelection=objPageElements.elcontent.getElement("div#far-download_mngr_selection tr[title="+strPageNumbers+"]")
	if(!$defined(elRowSelection)){
		var hashDownloadManagerPages=new Hash.Cookie('downloadmanager', {duration: 3600, path: '/'});
		if(!hashDownloadManagerPages.has(strId)){
			hashDownloadManagerPages.set(strId, strPageNumbers);
		}	
		
		//start animating
		var elDiv=elRow.getElement("td.far-right div.far-add")
		elDiv.addClass('busy');
		//elDiv.getParent().setStyle('text-align', 'left')
		//elDiv.getParent().setStyle('padding-right', 0)
		//return;
		statsStorePageEvent({eventname: 'download_add', value1: strPageIdSystem, value2: getCssSelector(elDiv.getFirst())});
		
		
		(function(){
			elDiv.setStyle('display','none');
			elDiv.getParent().removeProperty('style')
			elDiv.getParent().getElement('.far-remove').setStyle('display','inline');		
			elDiv.removeClass('busy')
		}).delay(1000);
	
		(function(){
			downloadManagerUpdateSelection();
		}).delay(950);

	}else{
		alert('This element is already in your list and cannot be added twice.');
	}
	return;
	

	
}

function downloadManagerUpdateSelection(){
	
	var objData={todo: '', todo2: ''};
	var objRequest = new Request.HTML({
		method: 'post',
		url: 'display_selection.asp',
		data: objData,
		onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
			//alert(responseHTML);
			$('far-download_selection').set('html', responseHTML);
			objPageElements.eldwnlheader=objPageElements.elcontent.getElement("div#far-download_mngr_selection_header div.far-full div.far-title");
			objPageElements.eldwnlheader.highlight('#FFF', '#91c7ff');
			//objPageElements.elcontent.getElement("div#far-download_mngr_selection_header div.far-top").highlight('#91c7ff', '#73BAFF');
			//buttonDownloadAllCalculateState();
		}
	
	}).send();	
	
}

function downloadManagerGenerateStart(strIndex, strPages){
	//exectutes the events required for generating a custom pdf file.
	
	//1) store the desired page ranges in the database
	var objData={index: strIndex, pages: strPages};
	var objRequest = new Request.HTML({
		method: 'post',
		url: 'generate_pdf.asp',
		data: objData,
		onRequest: function(){
			//show the loading indicator
			var elTarget=objPageElements.elbody.getElement('div.far-controls');
			var objCoordinates=elTarget.getCoordinates();
			
			//generate a ew dive to place over the button that indicates that the pdf id being generaed
			var elDivLoader=new Element('div', { 'class':'far-page_busydownload'}).inject($(document.body));
			elDivLoader.setStyles({
				'visibility': 'visible',
				'top': objCoordinates.top,
				'left': objCoordinates.left,
				'width': objCoordinates.width,
				'height': objCoordinates.height
			})
			
		},
		onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
			//2) generate the pdf and store the file on the server
			var strUrlGenerator="generate_pdf.aspx?id="+responseHTML.clean();
			
			var objRequestNested = new Request.HTML({
				method: 'post',
				url: strUrlGenerator,
				onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
					//3) retrieve the filename of the generated pdf on the server
					//alert(responseHTML);
					strUrlPdf=responseHTML.clean();

					var elDivLoader=objPageElements.elbody.getElement('div.far-page_busydownload');
					elDivLoader.destroy();
					location.href=strUrlPdf;
				}
			}).send();					

		}
	}).send();		

}

/* Download button state */
function buttonDownloadAllCalculateState(){
	//set the button to the correct state
	var hashDownloadManagerPages=new Hash.Cookie('downloadmanager', {duration: 3600, path: '/'});
	var intLength=hashDownloadManagerPages.getKeys().length;
	intSelectionLength=intLength;
	//alert(intLength);
	if(intLength==0){
		buttonDownloadAllSetState('disabled');
	}else{
		buttonDownloadAllSetState('active');				
	}	
	
}

function buttonDownloadAllSetState(strType){
	var elImgNorm=objPageElements.elcontent.getElement("div.far-generate_active");
	var elImgHover=objPageElements.elcontent.getElement("div.far-generate_hover");
	var elImgDisabled=objPageElements.elcontent.getElement("div.far-generate_disabled");
	
	switch(strType){
		case 'active':
			elImgNorm.setStyle('display', 'inline');
			elImgHover.setStyle('display', 'none');
			elImgDisabled.setStyle('display', 'none');
			break;
		case 'hover':
			elImgNorm.setStyle('display', 'none');
			elImgHover.setStyle('display', 'inline');
			elImgDisabled.setStyle('display', 'none');
			break;		
		case 'disabled':
			elImgNorm.setStyle('display', 'none');
			elImgHover.setStyle('display', 'none');
			elImgDisabled.setStyle('display', 'inline');
			break;		
		
	}	
}


/* Show / hide selection */
function downloadManagerShowHideSelection(strType){
	
	var elSelectionHeaderClassNode=objPageElements.elcontent.getElement("table.far-download_mngr_selection_header_wrapper td.far-center");
	var elSelectionWrapper=objPageElements.elcontent.getElement("div#far-download_mngr_selection_wrapper");
	var elSelectionContent=elSelectionWrapper.getElement('div#far-download_mngr_selection');
	var hashPanelState=new Hash.Cookie('panelstate', {duration: 3600, path: '/'});
	
	if(strType=='show'){
		elSelectionHeaderClassNode.addClass('far-selection_opened');		
		elSelectionHeaderClassNode.removeClass('far-selection_closed');
		
		
		//animate
		var intNewHeight=elSelectionContent.getSize().y;
		elSelectionWrapper.tween('height', intNewHeight);		
		
		//store the state in a Cookie		
		hashPanelState.set('state', 'opened');
			
	}else{
		elSelectionHeaderClassNode.addClass('far-selection_closed');
		elSelectionHeaderClassNode.removeClass('far-selection_opened');
		//elSelectionWrapper.addClass('far-selection_closed');
		//elSelectionWrapper.removeClass('far-selection_opened');	
		
		elSelectionWrapper.tween('height', 0);		
		
		//store the state in a Cookie		
		hashPanelState.set('state', 'closed');				
		
	}
	
	
}

function initDownloadManager(){

	var elSelectionWrapper=objPageElements.elcontent.getElement("div#far-download_mngr_selection_wrapper");
	
	elSelectionWrapper.set('tween',{
		duration: 800,
		transition: Fx.Transitions.Cubic.easeInOut,
		onComplete: function(el){
			var strPanelState;
			if(el.getSize().y > 20){
				el.addClass('far-selection_opened');
				el.removeClass('far-selection_closed');
				strPanelState='opened';	
			}else{
				el.addClass('far-selection_closed');
				el.removeClass('far-selection_opened');		
				strPanelState='closed';		
			}
			el.removeProperty('style');
			
			//store the state in a Cookie
			var hashPanelState=new Hash.Cookie('panelstate', {duration: 3600, path: '/'});
			hashPanelState.set('state', strPanelState);
			
		},
		link: 'chain'
	});	
	
	objPageElements.eldwnlheader=objPageElements.elcontent.getElement("div#far-download_mngr_selection_header div.far-middle table.far-download_mngr_selection_header_wrapper");
	//objPageElements.eldwnlheader=objPageElements.elcontent.getElement("div#far-download_mngr_section_downloads div.far-header h3");
	
	//to track the full download movie
	var elLink=$('download_full_1-2');
	statsLinkSetEvent(elLink);
	
}