// JavaScript Document
// JavaScript Document
var e = jQuery.Event("click"); 

function bookmarks_popup(object){
	//getting height and width of the message box
	offset=jQuery(object).offset()
	offsetdoc=jQuery("#contenaire").offset();
  
    //getting height and width of the message box
    var height = jQuery('#popuup_div').height();
    var width = jQuery('#popuup_div').width();
    //calculating offset for displaying popup message
	if (jQuery.browser.msie)
	    leftVal=(offset.left-offsetdoc.left +width/2 -50)+"px";
	else
	    leftVal=(offset.left-offsetdoc.left +width/2-50)+"px";
    topVal=offset.top+"px"; 
    //show the popup message and hide with fading effect
    jQuery('#popuup_div').css({left:leftVal,top:topVal}).show().fadeOut(5000);
      

	
}
function cookie_addlist(chkname,id){
	var listchecked=jQuery.cookie(chkname);
	var badd=true;
	if (listchecked){
		listcheckedarray=listchecked.split('|');
		if (listcheckedarray.length<3){
			
			//verify if already exist -> do not add
			for(var i=0;i<listcheckedarray.length;i++){
				if (listcheckedarray[i]==id) { badd=false; }
				
			}
			if (badd){
				listchecked=listchecked+('|')+id;
				jQuery.cookie(chkname, listchecked, { path: '/'});
			}
		}
	}else{
		jQuery.cookie(chkname,id,{ path: '/'});
	}

}
function cookie_dellist(chkname,id){
	var listchecked=jQuery.cookie(chkname);
	var newlistchecked='';
	if (listchecked){
		listcheckedarray=listchecked.split('|');
		for(var i=0;i<listcheckedarray.length;i++){
			//rebuild list without this id
			if (listcheckedarray[i]!=id){
				if (newlistchecked)
				newlistchecked=newlistchecked+('|')+listcheckedarray[i];						
				else
				newlistchecked=listcheckedarray[i];
			}
						
		}
		jQuery.cookie(chkname, newlistchecked,{path: '/'});
	}

}
function cookie_empty(chkname){
	jQuery.cookie(chkname, '',{path: '/'});
}

function cookie_getchecked(object,chkname){
	var listchecked=jQuery.cookie(chkname);
	var newlistchecked='';
	if (listchecked){
		listcheckedarray=listchecked.split('|');
		for(var i=0;i<listcheckedarray.length;i++){
			if(chkname=='chklens'){
				if (listcheckedarray[i]==object.id+'-'+object.cameraId){
					return 'checked';
				}
			}else{
				if (listcheckedarray[i]==object.id){
					return 'checked';
				}
			}
		}
	}
	return '';
}
// add - object is the clicked button for adding
function bookmarks_addCamera(id,object) {
	if (object)	bookmarks_popup(object);
	if (isNaN(id)) id=0;
	cookie_addlist('chkcamera',id);
	jQuery.ajax({
				type: "GET",
				url: "/dakdata/bookmark/addProductCookie.php", 
				data: "cameraId="+id,
				success: function(){ getBasket('camera');}
				});
}

function bookmarks_addLens(id, camera_Id,object) {
	if (object) bookmarks_popup(object);
	if (isNaN(camera_Id)) camera_Id=0;
	if (isNaN(id)) id=0;
	cookie_addlist('chklens',id+'-'+camera_Id);
	jQuery.ajax({
				type: "GET",
				url: "/dakdata/bookmark/addProductCookie.php", 
				data: "lensId="+id+"&cameraId="+camera_Id,
				success: function(){ getBasket('lens'); }
				});
}

function bookmarks_removeCamera(id) {
	cookie_dellist('chkcamera',id);
	jQuery.ajax({
				type:"GET",
				url:"/dakdata/bookmark/removeProductCookie.php", 
				data:"cameraId="+id,
				success:function(){ getBasket('camera');}
				});
}

function bookmarks_removeLens(id, camera_Id) {
	cookie_dellist('chklens',id+'-'+camera_Id);
	jQuery.ajax({
				type:"GET",
				url:"/dakdata/bookmark/removeProductCookie.php",
				data:"lensId="+id+"&cameraId="+camera_Id,
				success:function(){ getBasket('lens'); }
				});
}

/*
	Comparaison d'appareils
*/
function bookmarks_compareCameras(ids) {
	var str = ids.join('|');
	jQuery.ajax({
   	type: "GET",
   	url: "/dakdata/bookmark/compareProduct.php",
   	data: {type: 'sensor', listId: str, url: g_tpl_URL['comparesensor']},
   	success: function(msg){
	    eval(msg);
   	}
 	});
}


/*
	Comparaison de lentilles
*/
function bookmarks_compareLenses(ids,couples) {
	var str = ids.join('|');
	var str2 = couples.join('|');
	//alert(str +'--' + str2);
	jQuery.ajax({
   	type: "GET",
   	url: "/dakdata/bookmark/compareProduct.php",
   	data: {type: 'optics', listId: str, listCameraId: str2, url: g_tpl_URL['compareoptics']},
   	success: function(msg){
		if (msg)   eval(msg);
   	}
 	});
	
}


/*
	Vérification du nombre nbmax de cases à cocher
*/
function checkboxLimitCheck(checkbox, checkboxGroup, nbmax, chkname) {
	var count = 0;
	var listchecked=""
	checkboxGroup.each(function() {
		if (this.checked){
			count++;
			
		}
	});
	if (count > nbmax) {
		checkbox.attr('checked', false);
        
		if (chkname=='chkcamera')
		jQuery("#compare1msg").html('You can select up to ' + nbmax + ' items');
		else
		jQuery("#compare2msg").html('You can select up to ' + nbmax + ' items');


	}else{
				
		jQuery("#compare1msg").html('');
		jQuery("#compare2msg").html('');
	}
}

function showRowSelectState(checkbox,chkname) {
	var row = checkbox.parent().parent();
	var state = checkbox.attr('checked');
	var id='';
	if (chkname=='chklens') id=jQuery(checkbox).attr('value')+'-'+ jQuery(checkbox).attr('cameraid');
		else id=jQuery(checkbox).attr('value');
	//alert(id);
	if (state){
		row.addClass('selected');		
		cookie_addlist(chkname,id);
	}
	else{
		row.removeClass('selected');
		cookie_dellist(chkname,id);
	}
}

/*
	Construit une ligne du tableau
	(1 appareil ou 1 lentille)
*/
function basketRow(object, chkname, removeFct)
{
	var checkedstr=cookie_getchecked(object,chkname);
	
	
	if (chkname=='chklens')
	checkbox = jQuery('<input type="checkbox" '+checkedstr+'>').attr(	
		{'value': object.id, 'name': chkname,'cameraid':object.cameraId});
	else
		checkbox = jQuery('<input type="checkbox" '+checkedstr+'>').attr(	
		{'value': object.id, 'name': chkname});
	
	checkbox.click(function() {
		var checkGroup = jQuery('input[name=' + chkname + ']');
		checkboxLimitCheck(jQuery(this), checkGroup, 3,chkname);
		showRowSelectState(jQuery(this),chkname);
	});
	
	
	deleteLink = jQuery('<a href="javascript:"></a>').addClass('action').html('<img  src="/design/ezwebin/images/boutons3/btn_delete.png" border="0"/>');
;
	deleteLink.click(function() {
							  if(object.camera_Id!=null || object.camera_Id!=0){
								  removeFct(object.id, object.camera_Id);
								  }
							  else
							  	removeFct(object.id);
		//return false;
	});
	
	cell_thumbnail = jQuery('<div>').addClass('cell_thumbnail').append(jQuery('<img>').attr({src:object.imgpath}));
	if (object.status=="1"){ //display checkbox only for tested
		cell_status=jQuery('<div>').addClass('tagnewdata').html( g_lang_str["datatested"] )
	}else{
		cell_status=jQuery('<div>').addClass('tagnewdata').html( g_lang_str["datapreview"] )
	}
	//if (object.status=="1"){ //display checkbox only for tested
	if (1){
		cell_check = jQuery('<div>').addClass('cell_check')
		.html( ' Compare').prepend(checkbox);
	}else{
		cell_check = jQuery('<div>').addClass('cell_check')
		.html( ' Measurements not available');
	}
	cell_name = jQuery('<div>').addClass('cell_name')
		.html( object.name )
	if (chkname=='chklens')
	cell_cameraname = jQuery('<div>').addClass('cell_name')
		.html( object.cameraName )
	else
	cell_cameraname = jQuery('<div>').addClass('cell_name')
		.html( '&nbsp;' )

	cell_actions = jQuery('<div>').addClass('cell_act').append(deleteLink);
	if (chkname=='chklens')
	{ row = jQuery('<div>')
		.addClass('bookmarks_item')
		.append(cell_name)		
		.append(cell_thumbnail)	
		.append(cell_cameraname)	
		.append(cell_status)	
		.append(cell_check)
		.append(cell_actions); }
	else
		{ row = jQuery('<div>')
		.addClass('bookmarks_item')
		.append(cell_name)		
		.append(cell_thumbnail)	
		.append(cell_cameraname)
		.append(cell_status)	
		.append(cell_check)
		.append(cell_actions); }
	return row;
}

/*
	getBasket
	
	Charge les signets depuis le serveur, remplit les tableaux
*/
function getBasket(type)
{
	jQuery('#bookmarks_block'+type).html('<table width="100%"><tr><td align="middle" height="100"><img src="/design/ezwebin/images/background/ajax-loader.gif"/></td></tr></table>');
	jQuery.getJSON("/dakdata/bookmark/getProductCookie.php",
		function(data){
			var mainDiv = jQuery('#bookmarks_block'+type);
			var formDiv = jQuery('#bookmarks_form');
			var itemtype=type;
			//mainDiv.addClass('bookmarks_block');
			couples = [];
			
			// Tableaux de sélection
			var closediv=jQuery('<div>');
			
			/*var cart1 = jQuery('<div>')
				.addClass('table_bookmarks');
			var cart2 = jQuery('<div>')
				.addClass('table_bookmarks');*/
			
			var tableauEntete;
			mainDiv.empty();

			// Commandes "comparer"
			if (itemtype=='camera'){
				var compare1 = formDiv					
					.html('<a href="#toggleBookmarks" class="navbt-on bookmarkbt" >'+g_lang_str['Compare_measures']+'</a>')
					.click(function() {
						ids = [];					
						
						var checkGroup = jQuery('input[name=chkcamera]:checked');
						checkGroup.each(function() {
							ids.push(jQuery(this).attr('value'));					 
						});
		
						if (ids.length){
							jQuery("#compare1msg").html("");											
							bookmarks_compareCameras(ids);	
						}
						else{
							jQuery("#compare1msg").html(g_lang_str['no_item_bookmark_checked']);
						}
	
					});
				
				
				// Remplissage des tableaux
				if (data){
					jQuery.each(data.camera, function(i, camera){
						camera.imgpath =  camera.thumbnail;
						mainDiv.append(basketRow(camera, 'chkcamera', bookmarks_removeCamera));
					});
					if (data.camera.length > 0){
					/* no more tabs 
					jQuery("#tabs").tabs( "enable" ,1) // selection le tab select item
					jQuery("#tabs").tabs( "enable" ,2) // selection le tab select item
					*/
					//jQuery("#tabs").tabs( "select" ,1) // selection le tab select item
					/*mainDiv.append(compare1)*/
								
						
					}else{
						mainDiv.append(jQuery('<p>').text(g_lang_str['no_item_bookmark']));
						/* no more tabs 
						jQuery("#tabs").tabs( "select" ,0) // selection le tab select item
						jQuery("#tabs").tabs( "disable" ,1) // selection le tab select item
						*/

					}
						
				}else{
						mainDiv.append(jQuery('<p>').text(g_lang_str['no_item_bookmark']));

				}
			}else{
			var compare2 = formDiv
				.html('<a href="javascript:" class="navbt-on bookmarkbt">'+g_lang_str['Compare_measures']+'</a>')
				.click(function() {
					ids = [];
					couples = [];
					var checkGroup = jQuery('input[name=chklens]:checked');
					checkGroup.each(function() {
						ids.push(jQuery(this).attr('value'));
						couples.push(jQuery(this).attr('cameraid'));
					});
					if (ids.length){
						jQuery("#compare2msg").html("");											
						bookmarks_compareLenses(ids,couples);	
					}
					else{
						jQuery("#compare2msg").html(g_lang_str['no_item_bookmark_checked']);
					}
					
				});
				
				if (data){
					jQuery.each(data.lens, function(i, lens){
						lens.imgpath = lens.thumbnail;
						lens.camera_Id = lens.cameraId;
						mainDiv.append(basketRow(lens, 'chklens', bookmarks_removeLens));
						couples.push(lens.cameraId);
					});
					if (data.lens.length > 0){						
						/*mainDiv.append(compare2);*/
						/* no more tabs 
						jQuery("#tabs").tabs( "enable" ,1) // selection le tab select item
						*/
						//jQuery("#tabs").tabs( "select" ,1) // selection le tab select item


					}
					else{
						mainDiv.append(jQuery('<p>').text(g_lang_str['no_item_bookmark']));
						/* no more tabs 
						jQuery("#tabs").tabs( "select" ,0) // selection le tab select item
						jQuery("#tabs").tabs( "disable" ,1) // selection le tab select item
						*/

					}
				}else{

						mainDiv.append(jQuery('<p>').text(g_lang_str['no_item_bookmark']));

				}
			
			}
			/*var fermer = jQuery('<div style="display:block; z-index:0">')
						.append(jQuery('<a href="#" style = "border-color:white;"><img style="float:right; border-color:white;" src="/design/ezwebin/images/close.jpg"></img></a>')
						.click(function() {
							mainDiv.hide();									   
									   }));*/
			
			
			
		}
	);
}


