(function($) {
    $.fn.toggleDisabled = function(){
        return this.each(function(){
            this.disabled = !this.disabled;
        });
    };
})(jQuery);

function get_cd(id,collec){
	$("#cdrom_left > a").removeClass("active");	
	$("#"+id+"_"+collec).addClass("active");
	$("#cdrom_cd").load("/cdrom/index/load",{idTheme:id,collec:collec},function(){
	});
	
}

function saveAddKey(){
	$("#retourajaxsucess").html("");
	var newkey = $("#new_key").val();
	$.post("/admin/language/processaddkey",{newkey:newkey},function(data){
		$("#retourajaxsucess").fadeOut("fast").fadeIn().html(data);
	});
	
	
}
/**
 * popup for image detail
 * @param imageId
 * @return
 */
function mypopup(imageId,searchId)
 {
	
  window["mywindow"] = window.open ("/recherche/imagedetail?searchId="+searchId+"&imageId="+imageId,
  "mywindow","toolbar=yes,menubar=no,status=no,location=0,status=0,scrollbars=no, width=1080,height=620,resizable=no");
     if(mywindow.window.focus){mywindow.window.focus();}
     mywindow.moveTo(0,0);
 } 

/**
* popup for image detail
* @param imageId
* @return
*/
function detail(alias,params, searchId){
    window.open ("/detail/"+params+"/"+alias+"/"+searchId,
    "mywindow"+alias,"toolbar=yes,menubar=no,status=no,location=0,status=0,scrollbars=no, width=1080,height=620,resizable=no");
//    if(mywindow.window.focus){mywindow.window.focus();}
    //mywindow.moveTo(0,0);
} 

function order_popup(type,orderId){
	window["mywindow"] = window.open ("/myaccount/index/popup?type="+type+"&orderId="+orderId,
			"mywindow","toolbar=yes,menubar=no,status=no,location=0,status=0,scrollbars=yes, width=1200,height=1698,resizable=yes");
	if(mywindow.window.focus){
		mywindow.window.focus();
	}
	mywindow.moveTo(0,0);
}

//function invoice_popup(invoiceId){
//	window["mywindow"] = window.open ("/myaccount/index/popupinvoice?invoiceId="+invoiceId,
//			"mywindow","toolbar=yes,menubar=no,status=no,location=0,status=0,scrollbars=no, width=842,height=595,resizable=no");
//	if(mywindow.window.focus){
//		mywindow.window.focus();
//	}
//	mywindow.moveTo(0,0);
//}

function morelikethis(imageId,searchId)
 {
	if (opener){
		opener.location = "/recherche?idsearch="+searchId+"&mlt="+imageId;
		opener.focus();
	}
	//if(opener.focus){opener.focus();}
 } 

function search(vals)
{
	if (opener){
		str = "";
		for (val in vals){
			str+=vals[val]+" ";
		}
		mywindow = opener.location = "/recherche?bs_string="+str;
	//	if(opener.focus){opener.focus();}
		opener.focus();
	}
} 

/* Ancienne fonction de changement de page pour la recherche en ajax */
function showSearchOptions(id){
	myFilter = $('#filter');
//	filters = $("#idsearch");
	myFilter.toggle('slow',function(data){
		elmt = myFilter.children();
		if (elmt.is("img")){
//			val =filters.val();
			$.get("/recherche/moresearchoption",{idsearch:id},function(data){
				myFilter.append(data);
					$('.checkBox').checkBox({"width":"15px","height":"15px"});
					//$(".multipleSelectCheckBox").multiSelect();
					$(".monoSelectCheckBox").monoSelect();
				elmt.remove();
				myFilter.children(".divWrap").show("slow");
			});
		}
	});

}

function pageChange(event){
	$("#formPage").submit();
}

var dialogDiv;

//**************************** USERS ****************************
// 
function toggleStatus(idUser,statusUser){
	var status = "";
	var texte = "";
	
	var status;
	var texte = "";
	
	if(statusUser){
		status = statusUser;
		if(statusUser == 0){
			texte = "user.suspend";
		}
		else{
			texte = "user.active";
		}
	}
	else{
		status = 0;
		texte = "user.suspend";
	}
	
	$.get("/confirm",{id:idUser,url:"/admin/users/processtogglestatus?status="+status,texte:texte},function(data){
		$("#dialogSLB").html(data);
		dialogDiv = $("#dialogSLB").overlay({
			expose: { 
		        color: '#666', 
		        loadSpeed: 200, 
		        opacity: 0.7 
	    		}, 
		    // disable this for modal dialog-type of overlays 
		    closeOnClick: false, 
		    // we want to use the programming API 
		    api: true 
		}).load();
	});
}

// **************************** INVOICE ****************************
function confirm_overlay(id,action,texte){
	var url = action;
	
	$.get("/confirm",{id:id,url:url,label:"confirm_form",texte:texte},function(data){
		$("#dialogSLB").html(data);
		dialogDiv = $("#dialogSLB").overlay({
			expose: { 
		        color: '#666', 
		        loadSpeed: 200, 
		        opacity: 0.7 
	    		}, 
		    // disable this for modal dialog-type of overlays 
		    closeOnClick: false, 
		    // we want to use the programming API 
		    api: true 
		}).load();
	});
}

function validateConfirm(action,id){
	$.get(action,{id:id},function(data){
		$("#dialogSLB").html(data.msg);
		dialogDiv = $("#dialogSLB").overlay({
			expose: { 
		        color: '#666', 
		        loadSpeed: 200, 
		        opacity: 0.7 
	    		}, 
		    // disable this for modal dialog-type of overlays 
		    closeOnClick: false, 
		    // we want to use the programming API 
		    api: true 
		}).load();
	},"json");
	close_overlay();
	setTimeout(function(){window.location.reload();},200);
}

/////////////////// Small Light Box UI Functions

/**
 * Closes the overlay when the 
 * cancel button is clicked
 */
function close_overlay(){
	$("#dialogSLB").overlay().close();
	clearTimeout(tO);
}

/**
 * Open/Close the small lightbox
 * @param none
 * @return none
 * 
 */
function toggleSmallLightBox(){
	
	 // Récupération des infos d'état de la SLB dans le DOM
	var slb_DOM_state = $('#Btoggle').attr("class");
	
	if(slb_DOM_state == ""){
		slb_DOM_state = "open";
		$('#Btoggle').attr("class","open");
		$("#maincontent").attr("class","open");
	    $("#lightboxSmallContainer").attr("class","open");
	}
	else if(slb_DOM_state == "close"){
		slb_DOM_state = "open";
		$('#Btoggle').attr("class","open");
		$("#maincontent").attr("class","open");
	    $("#lightboxSmallContainer").attr("class","open");
	}
	else{
		slb_DOM_state = "close";
		$('#Btoggle').attr("class","close");
		$("#maincontent").attr("class","close");
	    $("#lightboxSmallContainer").attr("class","close");
	}
	
	// Stockage du statut de la LB en session
	$.get("/session/setoption/index",{namespace:"lightbox",statut:slb_DOM_state},function(){
	});
}


/**
 * Populates the list of the lightboxes
 * of the current user and displays
 * the thumbnails in the small lightbox
 * 
 * @param int id_user
 * @return DOM
 * 
 */
function populate(currentSLB){
	// destruction du select existant
	$("#select_list_lb").empty();
	
	// Récupération de la SLB active
	var myObject = "<select id='list_slb' name='list_slb'></select>";
	$("#select_list_lb").html(myObject);
	
	$("#list_slb").load("/lightbox/index/populate",{currentSLB:currentSLB}, function(){
		
		if(currentSLB){
			newSLBname = currentSLB;
		}
		else{
			newSLBname = $("#list_slb").val();
//			newSLBname = $("#formLB").find("input:checked").val();
		}
//		alert(newSLBname);
		$("#name_smallLightBox").text($("#list_slb option:selected").text());
		
		$.post("/lightbox/index/currentlightbox",{newSLBname:newSLBname}, function(data){
//			alert(data)
			$("#slb_contenu").find("tr").html(data);
		});
//		$("#list_slb").text("")
//		alert(newSLBname)
		$("#list_slb").monoSelect(switchSLBv2,{});
	});
		
}

/**
 * 
 * Changement de SLB active
 * @param string previousSLBName
 * @return DOM
 *  
 */
//function switchSLB(previousSLBName){
//    var newSLBval = $("#list_slb option:selected").val();
//    var newSLBname = $("#list_slb option:selected").text();
//    $("#name_smallLightBox").text(newSLBname);
//
//    $.post("/lightbox/index/currentlightbox",{previous_slb:previousSLBName,newSLBname:newSLBval}, function(data){
//    	$("#slb_contenu").find("tr").html(data);
//    	$.get("/session/setoption/index",{namespace:"lightbox",active:newSLBval},function(){
//    	});
//    });
//}
function switchSLBv2(){
//	alert("switching")
    newSLBval = $("#formLB").find("input:checked");
    newSLBvalText = newSLBval.parent().text();
    if ($("#name_smallLightBox").text()!=newSLBvalText){
    	elem = $("#slb_contenu").find("tr");
	    $("#name_smallLightBox").text(newSLBvalText);
	    elem.fadeTo("fast",0,function(){
		    $.post("/lightbox/index/currentlightbox",{newSLBname:newSLBval.val()}, function(data){
		    	$("#slb_contenu").find("tr").html(data);
		    	elem.fadeTo("fast",1);
		    	$.get("/session/setoption/index",{namespace:"lightbox",active:newSLBval.val()},function(){
		    	});
		    });
	    });
    }
}

/**
 * 
 * Creation of a new lightbox
 * @param none
 * @return DOM
 * 
 */
function loadOverlay(url,options){
//	window.clearTimeout(tO);
	$.post(url,options, function(data){
		$("#dialogSLB").html(data);
		dialogDiv = $("#dialogSLB").overlay({
			expose: { 
		        color: '#666', 
		        loadSpeed: 200, 
		        opacity: 0.7 
	    		}, 
		    // disable this for modal dialog-type of overlays 
		    closeOnClick: false, 
		    // we want to use the programming API 
		    api: true 
		}).load();
//		dialogDiv.load();
		$("#formRenameLB").bind("keypress", function(e){ return submitRename(e);});
		$("#formCreateLB").bind("keypress", function(e){ return submitRename(e);});
		$("#formDeleteLB").bind("keypress", function(e){ return submitRename(e);});
	});
}

function createSLB(){
	window.clearTimeout(tO);
	tO = null;
//	alert(tO);
	loadOverlay("/lightbox/manage/create");
}

function deleteSLB(){
	window.clearTimeout(tO);
//	var val_lb = $("#formLB").find("input:checked");
//	alert(val_lb.val());
	loadOverlay("/lightbox/manage/delete");
}

function renameSLB(){
	window.clearTimeout(tO);
	loadOverlay("/lightbox/manage/rename");
}


/**
 * rename lightbox submission
 * @param form
 * @param event
 * @return
 */
 function submitRename(e){

    if (e.keyCode == 13 || e.which == 13){
    	envoi_form();
    	return false;
    }
 }

function shareSLB(){
//	var current_name = $("#list_slb").val();
	var current_name = $("#formLB").find("input:checked").val();
//	alert(current_name);
	loadOverlay("/lightbox/share/share",{current_name:current_name});

}

//function envoi_form(){
//	
//	var lightbox_name = $("#lightbox_name").val();
//	var current_name = $("#name_smallLightBox").text();
//	if(lightbox_name != ""){
//		var action = $("#dialogSLB > form").attr("action");
//		$.post(action, {lightbox_name:lightbox_name,current_name:current_name}, function(data){
//			pos = data.indexOf("::");
//			if(pos > 0){
//				overlay = data.substr(0,pos);
//				id_active = data.substr(pos+2,data.length);
//				$("#dialogSLB").html(overlay);
//				// Stockage du statut de la LB en session
//				$.get("/session/setoption/index",{namespace:"lightbox",active:id_active},function(){
//				});
//				setTimeout(function(){window.location.reload();},800);
//			}
//			else{
//				$("#dialogSLB").html(data);
//			}
//		});
//	}
//
//}

function envoi_form(){
	var lightbox_name = $("#lightbox_name").val();
//	var current_val = $("#selectVisionneuses").val();
//	var current_name = $("#name_smallLightBox").text();
	var current_val = $("#formLB").find("input:checked");

	if(lightbox_name != ""){
		var action = $("#dialogSLB > form").attr("action");
		$.post(action, {lightbox_name:lightbox_name,current_val:current_val.val()}, function(data){
			$("#dialogSLB").html(data.overlay);
			$.get("/session/setoption/index",{namespace:"lightbox",active:data.id_active},function(){
			});
		},"json");
	}
}

function envoi_share_form(){

    sender = $("#sender").val();
    
    subject = ($("#subject").val())?$("#subject").val():"lightbox sharing";

    comment = $("#comment").val();
    
    recipient = $("#recipient").val();

    sharing = $("input[id*=sharing]:checked").val();    // 0 = read-only; 1 = full

    lightbox = $("#formLB").find("input:checked").val();
    
    $.post("/lightbox/share/processshare",{sender:sender,subject:subject,recipient:recipient,comment:comment,sharing:sharing,lightbox:lightbox},function(data){
        var dialogDiv = $("#dialogSLB").overlay({
            expose: { 
                color: '#666', 
                loadSpeed: 200, 
                opacity: 0.7 
                }, 
            // disable this for modal dialog-type of overlays 
            closeOnClick: false, 
            // we want to use the programming API 
            api: true 
        }).load();
        $("#dialogSLB").html(data.msg);
    },"json");
}

/**
 * 
 * Ajout d'une vignette dans la SLB
 * @param string id
 * @param string dossier 
 * @return DOM
 * 
 */
function addSmallLightBox(id,dossier){  
	
	var box_name = $("#name_smallLightBox").text();
	
	if(box_name != ""){
		box_id = $("#formLB").find("input:checked").val();
	}
	else{
		box_id="empty";
	}
	
	$.post("/lightbox/manage/addpic",{box_id:box_id,id:id,dossier:dossier}, function(data){
		if(data.lb){
			if ($("#messageText").is(':visible')){
				$("#messageText").hide();
			}
			if (!$("#messageText").is(':visible') || $("#messageText").text()==""){
				$("#messageText").text(data.message);
				$("#messageText").show();
				tO = setTimeout(function(){
					$("#messageText").hide();
					
				},2000);
			}
			newSLBval = $("#formLB").find("input:checked").val();
			// Ouverture de la SLB
			$('#Btoggle').attr("class","open");
			$("#maincontent").attr("class","open");
		    $("#lightboxSmallContainer").attr("class","open");
			$("#slb_contenu").find("tr").append(data.img);
		}else{
			$("#dialogSLB").html(data.overlay);
			var dialogDiv = $("#dialogSLB").overlay({
			    // disable this for modal dialog-type of overlays 
			    closeOnClick: false, 
			    // we want to use the programming API 
			    api: true 
			});
			window.clearTimeout(tO);
			//	load it immediately after the construction 
			dialogDiv.onBeforeLoad(function(){
				$("#messageText").hide();
				if (dialogDiv.isOpened()){
					dialogDiv.close(); 
				}
			});
			dialogDiv.load();
			tO = setTimeout("close_overlay()",2000);
		}
	},"json");
	
	
}

/**
 * 
 * Enlève la vignette de la SLB
 * @param string id
 * @return none
 * 
 */
function removeThumb(id){
   
//	box_id = $("#list_slb option:selected").val();
	box_id = $("#formLB").find("input:checked").val();
	
	
	$("#"+id).remove();
	
    
    $.post("/lightbox/manage/removethumb",{id:id,box_name:box_id}, function(data){
    	
    	$("#dialogSLB").html(data.overlay);

    	url = window.location.pathname;
    	if(url == "/lightbox/visionneuse"){
    		setTimeout(function(){window.location.reload();},50);
    	}
    	else{
    		setTimeout("close_overlay()",800);
    	}
    	
    	// Stockage du statut de la LB en session
//    	$.get("/session/setoption/index",{namespace:"lightbox",active:data.id_active},function(){
//    	});
    },"json");
}

function removeThumb2(idPic,idLb,element){
	var box_id = idLb;
	var id = idPic;
	$("#sort_"+id).remove();
	
	$.post("/lightbox/manage/removethumb",{id:id,box_name:box_id}, function(data){
    	
    	$("#dialogSLB").html(data.overlay);

    	url = window.location.pathname;
    	if(url == "/lightbox/visionneuse"){
    		setTimeout(function(){window.location.reload();},50);
    	}
    	else{
    		setTimeout("close_overlay()",800);
    	}
    	
    	// Stockage du statut de la LB en session
//    	$.get("/session/setoption/index",{namespace:"lightbox",active:data.id_active},function(){
//    	});
    },"json");	
	
}

/**
 * 
 */
function addLBtoCart(){
	window.clearTimeout(tO);
	elem = $("#formLB").find("input:checked");
	box_id = elem.val();
	box_name = elem.parent().text();

	$.post("/lightbox/index/addlightboxtocart",{id:box_id}, function(data){
		$("#dialogSLB").html(data);
		var dialogDiv = $("#dialogSLB").overlay({
			expose: { 
		        color: '#666', 
		        loadSpeed: 200, 
		        opacity: 0.7 
	    		}, 
		    // disable this for modal dialog-type of overlays 
		    closeOnClick: false, 
		    // we want to use the programming API 
		    api: true 
		});
		window.clearTimeout(tO);
		// load it immediately after the construction 
		dialogDiv.onBeforeLoad(function(){
			tO = setTimeout(function() {
				if (dialogDiv.isOpened()){
					dialogDiv.close(); 
				}
		    }, 3000);	
		});
		dialogDiv.load();
		updateCart();
		url = window.location.pathname;
		if(url.search("cart")){
			setTimeout(function(){window.location.reload();},50);
		}
	//end get
	});
}

///////////////////////////// Small lightbox functions


/**
 * enter submission
 * @param form
 * @param event
 * @return
 */
 function submitKeyboard(form, event){
 	if (event.keyCode == 13)
	 	form.submit();
	return false;
 }
 

//				 SEARCH FUNCTIONS

/**
 * correction function for ortographic suggestion
 * @author nicolas
 * @version 2.2
 */

function orthoCorrect(badPattern, goodPattern,item){
    var query = $("#rechercheInput").val();
    $("#rechercheInput").val(query.replace(badPattern, goodPattern));
    $("#"+item).remove();
}


/**
 * Ajout de mot suggere
 * @author nicolas
 * @version 2.2
 */

function suggest(pattern,item){
    $("#rechercheInput").val($("#rechercheInput").val()+" "+pattern);
    $("#"+item).remove();
}
 
/**
 * 
 * Demande de ré initialisation de mot de passe
 * @param none
 * @return DOM
 * 
 */
function lostPassword(){
	$("#dialogSLB").load("/login/lostpassword/",function(){
			var dialogDiv = $("#dialogSLB").overlay({
				expose: { 
			        color: '#666', 
			        loadSpeed: 200, 
			        opacity: 0.7 
		    		}, 
			    // disable this for modal dialog-type of overlays 
			    closeOnClick: false, 
			    // we want to use the programming API 
			    api: true 
			});
			// load it immediately after the construction 
			dialogDiv .load();
	});
}

	
var tO=null;
function addCDToCart(idCD){
	window.clearTimeout(tO);
	$.get("/cart/add",{id:idCD,type:"cd"},function(data){
		$("#dialogSLB").html(data.msg);
		var dialogDiv = $("#dialogSLB").overlay({
			expose: { 
		        color: '#666', 
		        loadSpeed: 200, 
		        opacity: 0.7 
	    		}, 
		    // disable this for modal dialog-type of overlays 
		    closeOnClick: false, 
		    // we want to use the programming API 
		    api: true 
		});
		window.clearTimeout(tO);
		// load it immediately after the construction 
//		dialogDiv.onBeforeLoad(function(){
			tO = setTimeout(function() {
				if (dialogDiv.isOpened()){
					dialogDiv.close(); 
				}
		    }, 3000);	
//		})
			$("#cart .cartHeader .pa-icon-cart").html(data.nbItems);
		dialogDiv .load();
	},"json");
}	

function addImgToCart(idImage){
	$.get("/cart/add",{id:idImage,type:"image"},function(data){
		$("#dialogSLB").html(data.msg);
		window.clearTimeout(tO);
		var dialogDiv = $("#dialogSLB").overlay({
			expose: { 
		        color: '#666', 
		        loadSpeed: 200, 
		        opacity: 0.0
	    		}, 
		    // disable this for modal dialog-type of overlays 
		    closeOnClick: false, 
		    // we want to use the programming API 
		    api: true 
		});
		tO = setTimeout(function() {
			if (dialogDiv.isOpened()){
				dialogDiv.close(); 
			}
	    }, 3000);
		$("#cart .cartHeader .pa-icon-cart").html(data.nbItems);
		dialogDiv.load();
//		updateCart();
	//end get
	},"json");
}

function addImgFormatToCart(idImage,idFormat){
	window.clearTimeout(tO);
	$.get("/cart/add/addwithformat",{id:idImage,type:"image",format:idFormat},function(data){
		$("#dialogSLB").html(data);
		dialogDiv = $("#dialogSLB").overlay({
			expose: { 
		        color: '#666', 
		        loadSpeed: 200, 
		        opacity: 0.7 
	    		}, 
		    // disable this for modal dialog-type of overlays 
		    closeOnClick: false, 
		    // we want to use the programming API 
		    api: true 
		});
		window.clearTimeout(tO);
		// load it immediately after the construction 
		dialogDiv.onBeforeLoad(function(){
			tO = setTimeout(function() {
				if (dialogDiv.isOpened()){
					dialogDiv.close(); 
				}
		    }, 3000);	
		});
		dialogDiv.load();
        displayMessagePost = $("#returnToSearchDiv");
//        alert(displayMessagePost.length)
        if (displayMessagePost.length>=1){
            displayMessagePost.show("slow")
        }

	//end get
	});
}


function updateCart(){
	$.get("/cart/index/getNumberDocFromCart",{},function(data){
		$("#cart .cartHeader .pa-icon-cart").html(data+" items");
	});
}

function updateCartPrice(){
	$.post("/cart/index/cart",{},function(data){
		$('#cartView').html(data);
	});
}

function toggleFormat(idFormat,idProduct){
	$("#cart-loader").show();
	$.post("/cart/add/toggleformat",{format:idFormat,product:idProduct},function(data){
		updateCartPrice();
	});
}

function changeFormat(value,id){
	$("#cart-loader").show();
	$.ajax({url:"/cart/index/cart",
			async:false,
			dataType:'json',
			type: "POST",
			data:({format:value,product:id}),
			success:function(data){
				$("#cart-loader").hide();
				if($("#td-price-"+id).length>0){
					$("#td-price-"+id).html(data.price);
					$("#td-price-"+id).fadeIn("slow");
					if($("#discountPrice").length==0 || data.discountPrice==undefined){
						$("#td-price-"+id).parent().removeClass("priceWithDiscount")
					}else{
						$("#td-price-"+id).parent().addClass("priceWithDiscount")
					}
				}
				if($("#td-discount-price-"+id).length>0){
					$("#td-discount-price-"+id).html(data.discountPrice);
					$("#td-discount-price-"+id).fadeIn("slow");
				}
				if($("#totalPrice").length>0){
					$("#totalPrice").html(data.total);
					$("#totalPrice").fadeIn("slow");
				}
				if($("#discountPrice").length>0 && data.totalDiscount!=NaN){
					$("#discountPrice").html(data.totalDiscount);
					$("#discountPrice").fadeIn("slow");
				}
			}
	});
}

function validateCart(url){
	selection = 1;
	$(".cart_select_format").each(function(index){
		if($(this).val()==0){
			selection= 0;
		}
	});
	if(selection== 0){
		$("#dialogSLB").html($("#msgAttentionFormat").html());
		dialogDiv = $("#dialogSLB").overlay({
			expose: { 
		        color: '#666', 
		        loadSpeed: 200, 
		        opacity: 0.7 
	    		}, 
		    // disable this for modal dialog-type of overlays 
		    closeOnClick: false, 
		    // we want to use the programming API 
		    api: true 
		});
		window.clearTimeout(tO);
		dialogDiv .load();
	}else{
		window.location = url;
		//window.location = "/cart/licence/index?licence=1";		
	}
}

function dwl_popup(id_invoice,ponumber,date){
	window["mywindow"] = window.open ("/myaccount/mydownload?invoiceId="+id_invoice+"&po="+ponumber+"&date="+date,
			"mywindow","toolbar=yes,menubar=no,status=no,location=0,status=0,scrollbars=1, width=950,height=582,resizable=1");
	if(mywindow.window.focus){
		mywindow.window.focus();
	}
	mywindow.moveTo(0,0);
}

function dwl_get(id_invoice,ponumber,date){
	area = $("#downloadArea");
	$.get("/myaccount/mydownload",{invoiceId:id_invoice,po:ponumber,date:date},function(data){
		area.fadeOut("normal",function(){
			$("#downloadArea").html(data);
			area.fadeIn("normal",function(){
				
			});
		});

	});
}

function mouseover(event){
	img = $(this).attr("src");
	var url = root+img.replace("/T/", "/"+prefix+"/");
    urlPreview = url;
	image = new Image();
	image.src = url;
    position = $(this).position()
	image.onload = function() {
		$("#overlayImg > img").attr("src",url);
		left = position.left + 15;
		if (left-image.width<350)
			autoLeft=false;
		else autoLeft = true;
		var right='auto';
		if (autoLeft) {
			right = $(window).width() - left+60;
			left = 'auto';
		}else{
            right = 'auto'
            left = position.left + 220;
//            $("#leftHeaderDiv").text(left)
        }
		yOffset = getOffset();
		ypos = (event.pageY-yOffset["Y"]);
        $("#overlayImg").css({
            left: left,
            top: yOffset["Y"]+200,
            right:right
        });
		$("#overlayImg").fadeIn(400);
	};
}

// MODULE

function upload_popup(imageID){
	window["mywindow"] = window.open ("/admin/uploadimg?imageID="+imageID,
			"mywindow","toolbar=yes,menubar=no,status=no,location=0,status=0,scrollbars=0, width=300,height=300,resizable=0");
	if(mywindow.window.focus){
		mywindow.window.focus();
	}
	mywindow.moveTo(0,0);
}
function change_langue(lang) {
    
	$.post("/lang", {lang:lang}, function(){location.reload();});
        
}

/**
 * open popup 
 * @param imageId
 * @return
 */
function KW_popup(name, file, width, height, resizable, scrollbars)
 {
  window["mywindow"] = window.open (file,
  "mywindow","toolbar=yes,menubar=no,status=no,location=0,status=0,scrollbars="+scrollbars+", width="+width+",height="+height+",resizable="+resizable+"");
     if(mywindow.window.focus){mywindow.window.focus();}
     mywindow.moveTo(0,0);
}

//function switchCD(){
//	var idCollection =  $("#searchCdForm").find("input:checked").val();
//
//	$.get("/cdrom/index/switch",{idCollection:idCollection},function(data){
//		alert(data)
//	},"json")
//}
function procedurepopup(page){
	 window["mywindow"] = window.open ("/popup/"+page,
			  "mywindow","toolbar=yes,menubar=no,status=no,location=0,status=0,scrollbars=no, width=600,height=620,resizable=no");
			     if(mywindow.window.focus){mywindow.window.focus();}
			     mywindow.moveTo(0,0);
}

function saveTranslate()  {
       
        $("#retourajaxsucess").html("");
       
        var listeLangValue = "";
        $(".langvalue").each(function() {
                var value = $(this).val();
               
                // On recupère l'id lang pour l'array
                var idInput = $(this).attr('id');
                var _idInput = idInput.split('_');
                var idLang = _idInput[1];

                listeLangValue  += "&"+idLang+"="+encodeURIComponent(value);
               
        });
       
        var idLangKey = $(".idLangKey").val();
       
        $.post("/admin/language/update2",{idLangKey:idLangKey,listeLangValue:listeLangValue},function(data){
               $("#retourajaxsucess").html(data);
        });
}

function resendActivationEmail(){
	email = $("#login_email").val();
	if (email!=""){
		$.get("/login/index/resendactivationemail",{user:email },function(data){
			alert(data);
			$("#dialogSLB").html(data);
			dialogDiv = $("#dialogSLB").overlay({
				expose: { 
			        color: '#666', 
			        loadSpeed: 200, 
			        opacity: 0.7 
		    		}, 
			    // disable this for modal dialog-type of overlays 
			    closeOnClick: false, 
			    // we want to use the programming API 
			    api: true 
			});
			window.clearTimeout(tO);
			// load it immediately after the construction 
			dialogDiv.onBeforeLoad(function(){
				tO = setTimeout(function() {
					if (dialogDiv.isOpened()){
						dialogDiv.close(); 
					}
			    }, 3000);	
			});
			dialogDiv .load();
		});
	}
}


$.ctrl = function(key, callback, args) {
    $(document).keydown(function(e) {
        if(!args) args=[]; // IE barks when args is null
        if(e.keyCode == key.charCodeAt(0) && e.ctrlKey) {
            callback.apply(this, args);
            return false;
        }
    });
};

function emptyCart(){
	$("#dialogSLB").html($("#msgDeleteAttentionFormat").html());
	dialogDiv = $("#dialogSLB").overlay({
		expose: { 
	        color: '#666', 
	        loadSpeed: 200, 
	        opacity: 0.7 
    		}, 
	    // disable this for modal dialog-type of overlays 
	    closeOnClick: false, 
	    // we want to use the programming API 
	    api: true 
	});
	window.clearTimeout(tO);
	dialogDiv .load();
}

function toggleStatusVirtual(idEditor,statusVirtual){
	var status = "";
	var texte = "";
	
	if(statusVirtual){
		status = statusVirtual;
		if(statusVirtual == 0){
			texte = "virtual.editor.suspend";
		}
		else{
			texte = "virtual.editor.active";
		}
	}
	else{
		status = 0;
		texte = "virtual.editor.suspend";
	}
	
	$.get("/admin/virtualeditor/processtogglestatus",{idEditor:idEditor,status:status,texte:texte},function(data){
		$("#dialogSLB").html(data.texte);
		dialogDiv = $("#dialogSLB").overlay({
			expose: { 
		        color: '#666', 
		        loadSpeed: 200, 
		        opacity: 0.7 
	    		}, 
		    // disable this for modal dialog-type of overlays 
		    closeOnClick: false, 
		    // we want to use the programming API 
		    api: true 
		}).load();
		setTimeout(function(){window.location.reload();},200);
	},"json");
}


var getOffset = (function() { // Renvoie l'offset en X et Y d'un élément, sous forme d'objet
    if ( window.pageXOffset != undefined ) { // Safari, Firefox
        return function() { return { "X" : window.pageXOffset, "Y" : window.pageYOffset}; };
    }else{ // IE
        return function() { return { "X" : document.documentElement.scrollLeft, "Y" : document.documentElement.scrollTop}; };
    }
})();

$( function(){
	
	$('#login_account').keydown(function(event) {
		var keyCode = event.keyCode || event.which;
		if (event.keyCode == 13) {
			submitLogin();
			return false;
		}
	});
	
	function submitLogin() {
		$('#login_account').submit();
	}
	
//	$("#requestSearch").click( function (){
//		location.href = "mailto:research@photoalto.com";
//	});
	
	var element = $('#searchBar');
    if ($('#searchBar').length>0){
		var cale = $("#cale"); // DIV de 75px de hauteur masquée, que l'on affiche lorsque la searchBar passe en position fixed
		cale.height( ($("#frameSearchExtended").length != 0 ) ? '75px' : '30px' ); // On fixe hauteur de la cale à 75px , qui est la hauteur de la searchBar. On ne peut pas la calculer dyamiquement sans provoquer un bug sous Safari
		var offsetMax = 78; // Hauteur du header, valeur à partir de laquelle la searchBar passe en fixed
		$(window).scroll(function() {
			var offset = getOffset();
			if ( (offset["Y"] <= offsetMax)  ) {
				cale.hide();
				element[0].className = ""; // On enlève la classe fixedTop et on reset les propriétés de la searchBar
			}else if ( (offset["Y"] > offsetMax) ) {
				cale.show();
				element[0].className = 'fixedTop'; // On ajoute la classe fixedTop pour fixer la searchBar en haut de la page 
			}
	    });
    }
	$('.checkBox').checkBox({"width":"15px","height":"15px"});
//	$(".multipleSelectCheckBox").multiSelect();
	$(".monoSelectCheckBox").monoSelect();
//	$(".monoSelect").monoSelect();

	$("#displayOptions").click( function(event){
		var $id = event.target.id;	// Standard, thumbnails ou details
		var $cible = event.target; // Type <div>
		var $id_target = $cible.id;
		$(this).find('td').each( function(){
			var $id = $(this).attr("id");
			if($id != $id_target){
				$("td[id="+$id+"]").removeClass("hover");	
			}
			else{
				$("td[id="+$id+"]").addClass("hover");		
				$("td[id="+$id+"]").children('input').attr('checked',true);			}
		});
		$.get("/session/setoption",{namespace:"options",presentation:$("td[id="+$id+"]").children('input').val()},function(data){
			location.reload();
		});
		 
				 //		document.formResearch.submit();
	});
	$("#previewOptions").children("div.checkBox").click(function(event){
		event.stopPropagation();//alert($(this).find('input').attr("checked"))
		$.get("/session/setoption",{namespace:"options",imagePreview:$(this).find('input').attr("checked")},function(data){
			location.reload();
		});
	});
	$("#nb_p_page").click (function(event){
		var $cible = event.target; // Type <div>
		var $id_target = $cible.id;
		$(this).children('div')
		.each( function(){
			var $id = $(this).attr("id");
			if($id != $id_target){
				$("div[id="+$id+"]").removeClass("hover");
			}
			else{
				$("div[id="+$id+"]").addClass("hover");		
				$("div[id="+$id+"]").children('input').attr('checked',true);
			}
		});
		$.get("/session/setoption",{namespace:"options",nb_p_page:$("#nb_p_page input[type=radio]:checked").val()},function(data){
			location.reload();
		});
//		document.formResearch.submit();
	});
	
	
	
	$('#mltId').val('');	
	$("#rechercheBtn").click(function () {
		$("#filter").hide("slow");
	});

	if ($("#radioOldSearch").val()){
		$("#radioOldSearch").click(function(){
			if ($("#idsearch").val()!=""){
				state = $('#filter').css('display');
				if (state != "none")
					$('#filter').hide('slow');
//				$("#idsearch").val("");
				$("#rechercheInput").val("");
				$("#filter").html("<img src='/img/searchLoading.gif'></img>");
				if (state!="none")
					showSearchOptions($("#idsearch").val());
			}
		});
	}
	
	if ($("#radioNewSearch").val()){
		$("#radioNewSearch").click(function(){
			myFilter = $('#filter');
			elmt = myFilter.children();
			if (!elmt.is("img")){
//				showSearchOptions(0)
				$.get("/recherche/moresearchoption",{},function(data){
					myFilter.html("");
					myFilter.html(data);
					$('.checkBox').checkBox({"width":"15px","height":"15px"});
//					$(".multipleSelectCheckBox").multiSelect();
//					$(".monoSelectCheckBox").monoSelect()
////					
					myFilter.children(".divWrap").show("slow");
				});
			}else{
			}
		});
	}
	
	$(".recherche_cd_small > a").click( function(){
		var id_cd = $("#cd").val();
		
		if(id_cd == ""){
			var txt = $("#totranslate").html();
//			alert(txt)
			$("#dialogSLB").html(txt);
			dialogDiv = $("#dialogSLB").overlay({
				expose: { 
			        color: '#666', 
			        loadSpeed: 200, 
			        opacity: 0.7 
		    		}, 
			    closeOnClick: false, 
			    api: true 
			}).load();
		}
		else{
			$('#searchCdForm').submit();
		}
	});
	
	
	
	
	
	
	
});
