//
var currProject;
var currLayout;
var currPart;
var currTask;
var currCollection;
var currTopic=null;
var checkContentInterval;
var checkContentTaskInterval;
var fb_cb = new Object;
var singleEcard;

//
function initTools(){	
	//doAjaxUpdate('nav-content',"tools_get.php","id=null",onToolsLoaded);
   new Ajax.Updater('nav-content', "tools_get.php", {parameters: "id=null", method:"get",evalScripts:true,onComplete:function (req) {onToolsLoaded(req)}, onFailure:show_failure, onException:show_exception});					 
	 
	if (show_tb){
  	POP.Sekretariat.toggle(POP.Sekretariat.top, this);  		
  }	
}
function onToolsLoaded(s){
		//alert($('nav_content').tagName);

	applyBehaviour();
	if(user_id!=null){
			onToolsTabClick($("link_tab_0"));

			//el_str = "link_tab_0";
		//showLoading(el_str);
   // doAjaxUpdate(el_str,"tools_get_tab.php","tab=0",onToolsTabLoaded);
	}
	if (show_tb){

		onToolsTabClick($("link_tab_0"));
		if (show_tb_msg!='' && $('loginError'))
			setTimeout(function() {$('loginError').innerHTML = show_tb_msg+'<br class="clearer" />'},2000);
	}

	
}
function onToolsChanged(){
	applyBehaviour();
}
function onToolsInitialised(id){
    /* load first tab */
	//onToolsTabClick($("link_tab_0"));
}
function onToolsTabClick(el){
	//
	var a;
	var idAction;
	var i;
	//
    a = el.getAttribute("id").split("_");
    idAction = a.pop();
	a = document.getElementsByClassName("tools_tab");
	n = a.length;
    for(i=0;i<n;i++){
        $("tab_tools_"+i).style.display = "none";
        $("tab_tools_"+i).update("");
    }
    var tab_str  = "tab_tools_"+idAction;
    $(tab_str).style.display = "block";
    //
    loadToolsTab(tab_str,idAction);
	//
	return false;
}
function loadToolsTab(el_str,idAction){
	showLoading(el_str);
		var param = "tab="+idAction;

    doAjaxUpdate(el_str,"tools_get_tab.php",param,onToolsTabLoaded);
}
function onToolsTabLoaded(){ 
		if(getUserID()!=null){
			//$('username').value = "user"+user_id;
		}	
    applyBehaviour();
}
function onToolsSelectChanged(el){
	id = el.options[el.selectedIndex].value;
	currTopic = "project";
	currProject = id;
	
	param = 'project_id='+currProject;
	doAjaxUpdate('list_project_parts',"ajax/getProjectParts.php",param,'');
	

	//showProjectSheet(); 
}

function onPartSelection(el){
	currTask = currPart = 0;
	currPart = el.options[el.selectedIndex].value;
	
	/*if (el.selectedIndex>0)
		$('show_part_selection').style.display='block';
	else 
		$('show_part_selection').style.display='none';*/		
		
	
	if (el.selectedIndex==2) {
		showProjectSheetPart(1);
	}	
	else {
		
		showProjectSheetPart(); 
	}	
		
	//showPSEcards(currPart);
	//showProjectSheet(); 
}

function onPartSwitchAction(){
		
	//alert($('partSetCard_'+currPart));	
	
	showProjectSheetPart(1); 
}

function onTaskSelection(el){
	currTask = currPart = 0;
	currTask = el.options[el.selectedIndex].value;
		
	
	if (el.selectedIndex==2) {
		showProjectSheetTask(1);
	}	
	else {
		
		showProjectSheetTask(); 
	}	
}


function onToolsSelectChanged_reserve(el){ 
    //
    var topic;
    var id;
    var param;
    var elName;
	var a;
	var aEl = new Array('list_layout','list_part','list_project_actions','list_part_actions','list_thumbs_part','list_collection_actions','list_thumbs_collection');
    //
    topic = el.getAttribute("id");
    id = el.options[el.selectedIndex].value;
	//
	a = new Array();
	if(el.selectedIndex==0){
		//
		// clear links
		//
		elName = null;
		switch(topic){
        	case "collection":
				a = new Array(5,6);
				break;
        	case "project":
				a = new Array(0,1,3,4);
				break;
        	case "layout":
				a = new Array(1,3,4);
				break;
        	case "part":
				a = new Array(3,4);
				break;
		}
	}
	else{
    	//
		currTopic = "project";
    	switch(topic){
        	case "project":
				a = new Array(0,1,2,3,4);
            	elName = "list_layout";
				currTopic = "project";
				currProject = id;
            	break;
        	case "layout":
				a = new Array(1,3,4);
            	elName = "list_part";
				currTopic = "layout"; 
				currLayout = id;
            	break;
        	case "part":
				a = new Array(3,4);
            	elName = "list_thumbs_part";    
				currPart = id;     
				currTopic = "part";   
            	break;
        	case "collection":
            	elName = "list_thumbs_collection";
            	currCollection = id;
				currTopic = "collection";
            	break;
    	}
		//
    	param = "topic="+topic+"&id="+id;
		switch(topic){
			case "layout":
				param += "&pid="+currProject;
				break;
		}
		//
    	doAjaxUpdate($(elName),"tools_get_details.php",param,onToolsListLoaded);
    	//
	}
	for(var i=0;i<a.length;i++){
		emptyEl(aEl[a[i]]);
	}
}
function showProjectSheet(){ 
	window.clearInterval(checkContentInterval);
	loadList("task=projectsheet&id="+currProject);
	if (currProject)
		checkContentInterval = window.setInterval("checkContent()",300);

}

function showProjectSheetPart(showInfo){ 

	if (!showInfo)
		showInfo = 0;
		
	window.clearInterval(checkContentInterval);
	loadList("task=projectsheet&id="+currPart+"&show_info="+showInfo+'&project='+currProject);
	//loadList("task=basket&view=compare&id="+a.join(","));  
	if (currPart) 
		checkContentInterval = window.setInterval("checkContent("+showInfo+")",300);


}

function showProjectSheetTask(showInfo){ 

	if (!showInfo)
		showInfo = 0;
		
	window.clearInterval(checkContentTaskInterval);
	loadListPP("task=projectsheettask&id="+currTask+"&show_info="+showInfo+'&project='+currProject);
	if (currTask) 
		checkContentTaskInterval = window.setInterval("checkContentTask("+showInfo+")",300);


}

function onToolsSearchCategory(el){
	//
	var b;
	var i;
	//
	b = el.checked;
	a = $('tools_search_category').getElementsByClassName("checkbox");
	if(b){
		b = "checked";
	}
	else{
		b = "";
	}
	for(i=0;i<a.length;i++){
		a[i].checked = b;
	}
	
}
function checkContent(showInfo) {
				
	if ($('content').childNodes.length>1) {	
		//var x = getBrowser ();
			
		if (showInfo==0)  {
			showPSEcards(currPart);	
		}	
		else {
			getOptionsSchedule(currProject);
			setFeedbackhandler();
			enableSortables();	
			tmp = $$('div #project_sheet ul.projectsheet li.part_head');
			if (tmp.length>0) {
				for (i=0;i<tmp.length;i++)
					tmp[i].style.display='block';		
			}	
		}
		
		window.clearInterval(checkContentInterval);		
	}	
}

function checkContentTask(showInfo) {
				
	if ($('content').childNodes.length>1) {	
		//var x = getBrowser ();
			
		if (showInfo==0)  {
			showPSTaskEcards(currTask);	
		}	
		else {
			getOptionsSchedule(currProject);
			setFeedbackhandler();
			enableSortables();
			tmp = $$('div #project_sheet ul.projectsheet li.part_head');
			if (tmp.length>0) {
				for (i=0;i<tmp.length;i++)
					tmp[i].style.display='block';		
			}	
		}
		
		window.clearInterval(checkContentTaskInterval);		
	}	
}

function enableSortables() {	
		fb = $$('ul.partModels');

	for (i=0;i<fb.length;i++){
			Sortable.create(fb[i],{only:'projectsheet_model', onUpdate: updateModelOrdering});	
	}
			
}


function updateModelOrdering(obj) {
	
	if (!obj) {
	}
	else {
		var sorted = Sortable.sequence(obj);
		
		new Ajax.Request('ajax/setModelOrdering.php',{method: 'get', parameters: 'sort_order=' + sorted});
	}
	
}

function setFeedbackhandler(objId) {	
	cb_values = Array(0,1,0,2);
	cb_name_old = cb_name = '';
	cb_checked = false;
	is_artist = false;
	if (!objId)
		var objId = false;

	if (!objId)
		fb = $$('ul.projectsheet_feedback li input');
	else if ($('model_feedback_'+objId))
		fb = $$('ul#model_feedback_'+objId+' li input');
	else {
		fb = $$('ul#artist_feedback_'+objId+' li input');
		is_artist = true;
	}	
	
	if (fb.length<=0)
		fb = $$('ul.projectsheet_feedback li a');
		
		
	for (i=0;i<fb.length;i++){
		if (!fb[i].getAttribute('disabled')) {
			if (fb[i].checked)	
				cb_checked = fb[i].value;
			cb_name = fb[i].name.substring(fb[i].name.indexOf('[')+1,fb[i].name.indexOf(']')); 
		
			if ((cb_name!=cb_name_old) && (cb_checked)) {
				fb_cb[cb_name] = cb_checked;
				cb_checked = false;
			}	

			cb_name_old = cb_name;

			
			fb[i].onclick = function () {
				cb_name = this.name.substring(this.name.indexOf('[')+1,this.name.indexOf(']')); 

				if ((this.value==1) && (!confirm('do you want to remove this model from list?'))) {
					tmp = document.getElementsByName(this.name);
					
					this.checked = false;
					if (fb_cb[cb_name])
						tmp[cb_values[fb_cb[cb_name]]].checked = true;
					
					return false;
				}

				else if (this.value==1 || (this.tagName=='A' && this.getAttribute('type')=='remove' && confirm('do you want to remove this model from list?'))) {
					if (is_artist)
						this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode.parentNode.parentNode);					
					else
						this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode);
					this.value = 1;
				}

				
				
				fb_cb[cb_name] = this.value;
				param = "model="+this.name+'&value='+this.value+'&chk='+this.parentNode.parentNode.getAttribute('chk');
				
				if (this.value==2) {
					//elemLi = document.createElement('li');
					textNode = document.createTextNode('shortlist');
					
					//elemLi.appendChild(textNode);
					
					this.parentNode.parentNode.parentNode.replaceChild(textNode,this.parentNode.parentNode);
				}
				
				
				doAjaxUpdate('',"setFeedback.php",param, '');					
			}

		}
	}
	
	if (!objId) {
		fb_choice = $$('ul.projectsheet_choice li input');	

		for (i=0;i<fb_choice.length;i++){
			if (!fb_choice[i].getAttribute('disabled')) {					
				fb_choice[i].onclick = function () {	
					//alert(this.name);
					param = this.name+'='+this.value+'&value='+this.checked+'&chk='+this.parentNode.parentNode.getAttribute('chk');
					doAjaxUpdate('',"setFeedbackChoice.php",param, '');					
				}
			}
		}

		fb_rejected = $$('ul.projectsheet_feedback_rejected li a');
		for (i=0;i<fb_rejected.length;i++){
			if (!fb_rejected[i].onclick)
				fb_rejected[i].onclick = function () {	

					if (!confirm('do you want to remove this model from list?')) {				
						return false;
					}
					else {
						this.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode.parentNode);
					}
					param = "model="+this.getAttribute('id')+'&value=1&chk='+this.parentNode.parentNode.getAttribute('chk');
					doAjaxUpdate('',"setFeedback.php",param, '');					
				}

		}	
	}
}

function showPSEcards(part_id) {	
	//if (($('partPS_'+part_id).style.display=='block') && ($('partSetCard_'+part_id).childNodes.length==0)) {	

		
				
		param = "part="+part_id;
		new Ajax.Updater('', "getPartModels.php", {parameters: param, method:"get",evalScripts:true,onComplete:function (req) {showPSEcardsModels(req,part_id);}});									
	/*}
	else {
		showPSEcardsModelsLoaded(part_id);
	}*/
}



showPSEcardsModels = function (req,part_id) {	
	if (req.responseText) {
		param = "task=projectbasket&view=compare&id="+req.responseText+'&part_id='+part_id;

		if ($('imgLoading')) 
			$('imgLoading').style.display='block';			
		else 
			new Insertion.Top($('project_sheet'),'<img id="imgLoading" src="img/loading.gif" alt="lade" />');		
		
		new Ajax.Updater('partSetCard_'+part_id, "list_get.php", {parameters: param, method:"get",evalScripts:true,onComplete:function (req) {showPSEcardsModelsLoaded(part_id);}});								
		//doAjaxUpdate('partSetCard_'+part_id,"list_get.php",param, showPSEcardsModelsLoaded(part_id));
	}
	else {
		showPSEcardsModelsLoaded(part_id);
		alert('no entries found');

	}	
}

showPSEcardsModel = function (user_id,model_id,part_id) {	
	if ($('modelSetCard_'+model_id).hasChildNodes()) {
		//$('modelSetCard_'+model_id).style.display='none';
		$('modelSetCard_'+model_id).style.display='block';
		if ($('switchEcardSingle_'+model_id))
			$('switchEcardSingle_'+model_id).style.display='block';	
		$('modelFeedback_'+model_id).style.display='none';	
		
	}
	else {
		if (user_id) {
			singleEcard = model_id;
			param = "task=projectbasket&view=compare&id="+user_id+'&single='+model_id;
			doAjaxUpdate('modelSetCard_'+model_id,"list_get.php",param, showPSEcardsModelLoaded(model_id,part_id));
		}	

	}	
}
showPSEcardsModelLoaded = function (model_id,part_id) {	
//alert('end');
	$('modelSetCard_'+model_id).style.display='block';
	$('modelFeedback_'+model_id).style.display='none';	
	if ($('switchEcardSingle_'+model_id))
		$('switchEcardSingle_'+model_id).style.display='block';	
	
}
hidePSEcardsModel = function (model_id) {		
	$('modelSetCard_'+model_id).style.display='none';
	$('modelFeedback_'+model_id).style.display='block';		
	if ($('switchEcardSingle_'+model_id))
		$('switchEcardSingle_'+model_id).style.display='none';	
}

showPSEcardsModelsLoaded = function (part_id) {	

	if ($('partSetCard_'+part_id)) {
		if ($('partSetCard_'+part_id).style.display=='block') {		
			$('partSetCard_'+part_id).style.display='none';
			$('partPS_'+part_id).style.display='block';		
		}	
		else {
			$('partPS_'+part_id).style.display='none';		
			$('partSetCard_'+part_id).style.display='block';
			/*if ($('partSetCard_'+part_id).innerHTML=='')
				alert('Please select \'show current selection\' to view all selected models of this part.');*/

			//enablePSEcardsModels(part_id);
			//enableSortables();
		}	
	}

		if ($('imgLoading'))
			$('project_sheet').removeChild($('imgLoading'));
			

		//setTimeout('setFeedbackhandler()',2000);
}


enablePSEcardsModels = function (part_id) {	

//window.moveBy(0,6);
//alert("projectsheet");
	//applyBehaviour();
	

   // var el = $('ecard');
    //
   // applyBehaviour();
    //
   //new Sortable("partPS_"+part_id,{only:'projectsheet_model'});
		//new Draggable(part_id,{handle:'ecard_tools'});
//new Draggable('ecard',{handle:'ecard_tools'});
}

function addCartModels(part_id) {
	basketList = getItemsID();
	if (basketList!='') {
		param = 'list='+basketList+'&part_id='+part_id;
		//doAjaxUpdate('',"ajax/addCartModels.php",param, onToolsSelectChanged($('project')));
		
		//doAjaxUpdate('',"ajax/addCartModels.php",param, onPartSelection($('list_project_parts').getElementsByTagName('select')[0]));
		
		new Ajax.Updater('', "ajax/addCartModels.php", {parameters: param, method:"get",evalScripts:true,onComplete:function () {onPartSelection($('list_project_parts').getElementsByTagName('select')[0])} });		
		
	}	
}

// ######################### TASK / ARTISTS ###########################

function showPSTaskEcards(task_id) {					
		param = "task="+task_id;
		new Ajax.Updater('', "getTaskArtists.php", {parameters: param, method:"get",evalScripts:true,onComplete:function (req) {showPSEcardsArtists(req,task_id);}});									
}

showPSEcardsArtists = function (req,task_id) {	

	if (req.responseText) {
		param = "task=projectbasket&view=compare&id="+req.responseText+'&task_id='+task_id;

		if ($('imgLoading')) 
			$('imgLoading').style.display='block';			
		else 
			new Insertion.Top($('project_sheet'),'<img id="imgLoading" src="img/loading.gif" alt="lade" />');		
		
		new Ajax.Updater('taskSetCard_'+task_id, "list_get.php", {parameters: param, method:"get",evalScripts:true,onComplete:function (req) {showPSEcardsArtistsLoaded(task_id);}});								
// !!!!! Achtung Artist !!!!
	}
	else
		showPSEcardsArtistsLoaded(task_id);
}

showPSEcardsArtist = function (user_id,artist_id,task_id) {	

	if ($('artistSetCard_'+artist_id).hasChildNodes()) {

	
		$('artistSetCard_'+artist_id).style.display='block';
			
		if ($('switchEcardSingle_'+artist_id))
			$('switchEcardSingle_'+artist_id).style.display='block';
	
		$('artistFeedback_'+artist_id).style.display='none';			
	}
	else {
		if (user_id) {
			singleEcard = artist_id;
			param = "task=projectbasket&view=compare&id="+user_id+'&single='+artist_id;
			doAjaxUpdate('artistSetCard_'+artist_id,"list_get.php",param, showPSEcardsArtistLoaded(artist_id,task_id));
		}	
	}	

}




showPSEcardsArtistLoaded = function (artist_id,task_id) {	

	$('artistSetCard_'+artist_id).style.display='block';
	$('artistFeedback_'+artist_id).style.display='none';	
	if ($('switchEcardSingle_'+artist_id))
		$('switchEcardSingle_'+artist_id).style.display='block';	
	
}
hidePSEcardsArtist = function (artist_id) {		

	$('artistSetCard_'+artist_id).style.display='none';
	$('artistFeedback_'+artist_id).style.display='block';		
	if ($('switchEcardSingle_'+artist_id))
		$('switchEcardSingle_'+artist_id).style.display='none';	
}

showPSEcardsArtistsLoaded = function (task_id) {	

	if ($('taskSetCard_'+task_id).style.display=='block') {		
		$('taskSetCard_'+task_id).style.display='none';
		$('taskPS_'+task_id).style.display='block';		
	}	
	else {
		$('taskPS_'+task_id).style.display='none';		
		$('taskSetCard_'+task_id).style.display='block';
	}	
		if ($('imgLoading'))
			$('project_sheet').removeChild($('imgLoading'));
}


enablePSEcardsModels = function (part_id) {	
}

function addCartArtists(task_id) {

	basketList = getItemsID();
	if (basketList!='') {
		param = 'list='+basketList+'&task_id='+task_id;

		new Ajax.Updater('', "ajax/addCartArtists.php", {parameters: param, method:"get",evalScripts:true,onComplete:function () {onTaskSelection($('list_project_parts').getElementsByTagName('select')[1]); } });		
		
	}	
}



// ############################## ARTISTS ########################

function onToolsListLoaded(s){ 
    var b=false;
	switch(currTopic){
		case "collection":
			//
			//emptyEl('list_collection_actions');
			//
            topic = "collection_actions";
            elName = "list_collection_actions";
            id = currCollection;
            b = true;
            break;
		case "project":
            topic = "project_actions";
            elName = "list_project_actions";
            id = currProject;
            b = true;
            break;
		case "part":
            topic = "part_actions";
            elName = "list_part_actions";
            id = currPart;
            b = true;
            break;
	}
	if(b){
    	param = "topic="+topic+"&id="+id;
    	doAjaxUpdate($(elName),"tools_get_details.php",param, onToolsActionsLoaded);
    }
}
function onToolsActionsLoaded(s){ 
	onToolsChanged();
}
function onToolsActionClick(el){ 
	var param = getParam(el);
	var id = param.id;
	var idAction = param.idAction;
	//
	currTopic = "part";
	if(el.id.indexOf("collection")>-1){
		currTopic = "collection";
	}
	//
	if(currTopic.indexOf("collection")>-1){
		switch(Number(idAction)){
			case 0:
				loadList("task=collection&view=compare&id="+currCollection);
				break;
			case 1:
				deleteCollection(currCollection);
				break;
			case 2:
				sendLink("collection",currCollection);
				break;
			/*case 3:
				mergeLists("collection",currCollection);
				break;
			case 4:
				alert("save list as new collection");
				break;*/
		}
	}
	else if(currTopic.indexOf("part")>-1){
		switch(Number(idAction)){
			case 0:
				loadList("task=part&view=compare&id="+currPart);
				break;
			case 1:
				sendLink("part",currPart);
				break;
			/*	case 2:
				mergeLists("part",currPart);
				break;
			case 3:
				extendPart(currPart);
				break;*/
		}
	}
}
function extendPart(id){
	//
	var a;
	var n;
	var i;
	var aID;
	var param;
	//
    a = getListItems();
    n = a.length;
    if(n==0){
        alert("sorry, you can only add lists in compare view");
    }
    else{
        param = "id="+id+"&current="+getStringListID(a);
        doAjaxRequest("tools_part_extend.php",param,onPartExtended);
    }
}
function onPartExtended(s){
	new Insertion.Bottom("list_thumbs_part", s.responseText);
}
function addCollection(id){
	//
	var mode;
	//
	doAjaxRequest("collection_add.php","id="+id, onCollectionAdded);
}

function deleteCollection(id){
	doAjaxUpdate('tools_collection',"collection_delete.php","id="+id, onCollectionDeleted);
}
function onCollectionAdded(s){
	if($('tools_collection')){
		$('tools_collection').update(s.responseText);
	}
}
function onCollectionDeleted(s){
}

function setPrefPageCount(obj)  {
	param = "value="+obj.value;
	doAjaxRequest("ajax/setPrefPageCount.php",param,'');
}


function setPrefLightbox(obj)  {
	param = "value="+obj.value;
	doAjaxRequest("ajax/setPrefLightbox.php",param,'');
}


function downloadPartPdf(part_id) {
	cat=1;
	//param = "part_id="+part_id+"&cat="+cat;
	//doAjaxRequest(getBaseDirWeb()+"sedcard_zip_choose.php",param,'');	
	winDownload = window.open(getBaseDirWeb()+"sedcard_zip_choose.php?part_id="+part_id+"&cat="+cat,"download");
}
