$(document).ready(function() {
	/****************************************************************************************************************/
	// function to remove the $("#paradigm_all") checked, if one of the other checkboxes getting unchecked, or to add when all are checked
	
	var checkbox_checker = function(){ 
		var all_status = $("#paradigm_all").attr("checked");
		var ticked = $("input[name^='paradigm']:checked").length;
		//alert(ticked);
		var total = $("input[name^='paradigm']").length;
		//alert(total);
		
		if (ticked == total && all_status == false) {
			$("#paradigm_all").attr("checked", "checked");
		}else if(ticked < total && all_status == true){
			$("#paradigm_all").removeAttr("checked");
		}
	}
	
	/****************************************************************************************************************/
	// Default submit button check
	// TODO: Do this only on search page!! Not on all other pages!!
	// TODO: When not all checkboxes are checked, remove check from #paradigm_all
	
	var check_amount_products = function(){ 
	
		var howmanyfromsession = "";
		var howmanyonpage = $("input[name^='paradigm']:checked").length;
		if ( $("#admin").length == 0 ) {
			$.ajax({
				type: "POST",
				url: "/ajax_add_selected_product_to_session.php?global_check",
				success: function(msg){
					/* add here what to do on success */
					//alert(msg);
					howmanyfromsession =  msg;
					
					if (howmanyfromsession == 1){
						$(".amount").empty();
						$(".amount").append(' (Derzeit ist ' + howmanyfromsession + ' Produkt vorgemerkt)');
					}else if(howmanyfromsession > 1){
						$(".amount").empty();
						$(".amount").append(' (Derzeit sind ' + howmanyfromsession + ' Produkte vorgemerkt)');
					}else if(howmanyfromsession == 0){
						$(".amount").empty();
					}
					
					if(howmanyonpage == 0 && howmanyfromsession == 0) {
				    	//alert('None are checked on page');
						$(".requestbutton").attr("disabled", "disabled");
					}else if(howmanyonpage == 0 && howmanyfromsession > 0){
						//alert('At least one is checked');
						$(".requestbutton").removeAttr("disabled");
						$(".requestbutton").click(function(){
							$("#list").submit(); 
						});
					}
					
					$(".requestbutton").click(function(){
						if($("input[name^='paradigm']:checked").length > 0) {
							$("#list").submit();
						}
					});
				} 
			});
		}
	};
	
	// update display on page load
	check_amount_products();
	// check check / uncheck all checkbox
	checkbox_checker();

	/****************************************************************************************************************/
	// Search results list handling - on  a single checkbox event
	// colouring the rows
	// saving id's to session
	// disable and enable submit button

	// Change colour of selected row
	$('input:checkbox:not(#paradigm_all)').click(function(){ // exclude the $("#paradigm_all") checkbox!! $('input:checkbox:not(#paradigm_all)')
	
		var checked_status = this.checked;
		//alert(checked_status);
		
		var ver_id = $(this).val();
		//alert(ver_id);
		
		var name_current = $(this).parents("tr:eq(0)").attr('class');
		// alert(name_current);
	
		if(checked_status == true) {
			
			// submit button by default disabled, check if we need to anable the button
			if ($("input[name^='paradigm']:checked").length != 0) {
				$(".requestbutton").removeAttr("disabled");
			}
			
			//alert('checked'); 
			$(this).parents("tr:eq(0)").removeClass(name_current);
        	if(name_current == 'row1'){
				$(this).parents("tr:eq(0)").addClass('highlighttr1');
			}else if(name_current == 'row2'){
				$(this).parents("tr:eq(0)").addClass('highlighttr2');
			}
        	
			//add functionality to handle a check
			// save checked products to session
			$.ajax({
				type: "POST",
				url: "/ajax_add_selected_product_to_session.php?singleevent",
				data: "ver_id=" +ver_id,
				success: function(msg){
					/* add here what to do on success */
					//alert(msg);
				},
				complete: function(){
    				// update display of selected products
					check_amount_products();
					// check check / uncheck all checkbox
					checkbox_checker();
  				}

			});
			
    	}else{ 
			//alert('unchecked');
			
			
			// if none are checked, disable the submit button
			if ($("input[name^='paradigm']:checked").length == 0) {
				$(".requestbutton").attr("disabled", "disabled");
			}
			
        	if(name_current == 'highlighttr1'){
				$(this).parents("tr:eq(0)").removeClass(name_current);
				$(this).parents("tr:eq(0)").addClass('row1');
			}else if(name_current == 'highlighttr2'){
				$(this).parents("tr:eq(0)").removeClass(name_current);
				$(this).parents("tr:eq(0)").addClass('row2');
			}
        	
			//add functionality to handle an uncheck 
			// delete checked products from session
			$.ajax({
				type: "POST",
				url: "/ajax_unselected_products_from_session.php?singleevent",
				data: "ver_id=" +ver_id,
				success: function(msg){
					/* add here what to do on success */
					//alert(msg);
				},
				complete: function(){
    				// update display of selected products
					check_amount_products();
					// check check / uncheck all checkbox
					checkbox_checker();
  				}
			});
    	} 
	});
	
	/****************************************************************************************************************/
	// handling of check / uncheck all checkboxes
	
	$("#paradigm_all").click(function(){ 
    	var checked_status = this.checked; 
		var postdata = new Array();
		var save 	="";
		var remove 	="";
		
        $("input[name^='paradigm']").each(function(){ 
        	this.checked = checked_status; 
			
			var ver_id = $(this).val();
			//alert(ver_id);
		
			var name_current = $(this).parents("tr:eq(0)").attr('class');
			//alert(name_current);
			
			// build an array of all 
			postdata.push($(this).val()); 
			
			if(checked_status == true){
				
				remove = false; save = true;
				
				// add highlight
				$(this).parents("tr:eq(0)").removeClass(name_current);
	        	if(name_current == 'row1' || name_current == 'highlighttr1'){
					$(this).parents("tr:eq(0)").addClass('highlighttr1');
				}else if(name_current == 'row2' || name_current == 'highlighttr2'){
					$(this).parents("tr:eq(0)").addClass('highlighttr2');
				}
				
				// submit button by default disabled, check if we need to enable the button
				if ($("input[name^='paradigm']:checked").length != 0) {
					$(".requestbutton").removeAttr("disabled");
				}
				
			}else if(checked_status == false){
				
				save = false; remove = true;
				
				// remove highlight
				if(name_current == 'highlighttr1'){
					$(this).parents("tr:eq(0)").removeClass(name_current);
					$(this).parents("tr:eq(0)").addClass('row1');
				}else if(name_current == 'highlighttr2'){
					$(this).parents("tr:eq(0)").removeClass(name_current);
					$(this).parents("tr:eq(0)").addClass('row2');
				}
				
				// if none are checked, disable the submit button
				if ($("input[name^='paradigm']:checked").length == 0) {
					$(".requestbutton").attr("disabled", "disabled");
				}
			}
        });
		
		// save or remove in one go (outside the loop!)
		if(save){
			//alert(postdata);
			$.ajax({
				type: "POST",
				url: "/ajax_add_selected_product_to_session.php?postdata",
				data: "postdata=" +postdata,
				success: function(msg){
					/* add here what to do on success */
					//alert(msg);
				},
				complete: function(){
    				// update display of selected products
					check_amount_products();
					// check check / uncheck all checkbox
					checkbox_checker();
  				}
			});
		}else if(remove){
			//alert(postdata);
			$.ajax({
				type: "POST",
				url: "/ajax_unselected_products_from_session.php?postdata",
				data: "postdata=" +postdata,
				success: function(msg){
					/* add here what to do on success */
					//alert(msg);
				},
				complete: function(){
    				// update display of selected products
					check_amount_products();
					// check check / uncheck all checkbox
					checkbox_checker();
  				}
			});
		}
    });
	
	/****************************************************************************************************************/
	// TREESIZE MENUE
	// TODO: Run this only on Frontend pages
	// tree
	if ( $("#tree").length > 0 ) {
		$(function() {
			$("#tree").treeview({
				collapsed: true,
				animated: "medium",
				control:"#sidetreecontrol",
				persist: "cookie",
				cookieId: "navigationtree"
			});
		});
	}
	
	/****************************************************************************************************************/
	// IMAGE POPUP HANDLING
	
	$(".imageLink").click(function(){  
        $("#hidden").attr("src",$(this).attr('href'));  
         var href = $(this).attr('href');
		 //alert(this.id);
		 window.open('popup.php?img=' + href + '', 'packpilot', 'toolbar=no,location=yes,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,' + this.id + ',left=150,top=150');
		 return false;  
      });
	  
	  
	  
	  $("tr[link]>td").css("cursor","pointer");
	  $("tr[link]>td:not(:has(:checkbox))").bind("click", function(){
			//var link = $("tr[link]").attr("link");
			var link = $(this).parents("tr:eq(0)").attr('link');
       		window.location.href = link;
      });
	
	/****************************************************************************************************************/
	// Reset search box form
	$("#resetForm").click(function(){
		$("#sb")[0].reset();
		
		$("#sb")[0].vfo.value = '0';
		$("#sb")[0].hve.value = '0';
		$("#sb")[0].mat.value = '0';
		$("#sb")[0].vvar.value = '0';
		$("#sb")[0].tol.value = '50';
		
		$("#sb")[0].laenge.value = '';
		$("#sb")[0].breite.value = '';
		$("#sb")[0].hoehe.value = '';
		$("#sb")[0].durchmesser.value = '';
		$("#sb")[0].inhalt.value = '';
		$("#sb")[0].keyword.value = '';
		
		$("#default").attr("checked", "checked");
		
		// remove from session
		$.ajax({
			type: "POST",
			url: "/ajax_delete_vars_from_session.php"
		});

	});
	
	
	/****************************************************************************************************************/
	// USER BACKEND FUNCTIONS
	
	// Change window location
	$('#add_new_product').click(function(){
    	location.href='/users/user_products_edit.php?sub=add&new=1';
	});
	
	 $('#stop_dupli').click(function(){ 
        var ver_id = $('#cur_id').val();
		location.href='/users/user_products_edit.php?ver_id='+ver_id; 
     }); 
	 	 
	 $('div#add_new_zubehoer').hide();
	 
	 $('#add_access').click(function(){
	 	$('#add_new_zubehoer').slideToggle("fast");
	 });
	
	// Search box show / hide
	if ( $("#search_done_yes").length == 0 ) {
		$('#searchbox').hide(); // hide box on page load
	}
	
	$('a#search_box_link_open').click(function() {
		$('#searchbox').slideToggle("slow");
	});
	
	// Neues Produkteigenschaft vorschlagen
	$("div:[id*=box_]").hide();
	
	$('a.stop').click(function() {
		var pid = String(this.id);
		$('#box_'+pid).hide();
		
		$('#'+pid+'_neu').val("");
	
		$("[name="+pid+"]").removeAttr("disabled");
		$("[name="+pid+"]").disabled = false;
		
		$("[for="+pid+"]").removeAttr("style");
		
		return false;
	});
	
	$('a.jTip').click(function() {
		var pid = ""+String(this.id);
		$('#box_'+pid).show();
		
		$("[name="+pid+"]").attr("disabled", "disabled");
		$("[name="+pid+"]").disabled = true;
		
		$("[for="+pid+"]").css("color", "#CCCCCC");
		$("[for="+pid+"]").css("font-style", "italic");
		
		return false;
	});
	
	
	
	/****************************************************************************************************************/
	// ADMIN BACKEND FUNCTIONS
	
	// toogle manufacturer status
	$('#manufacturer').find('div.statusimg').click(function() {
		var divelement = this;
		var her_id = divelement.id;
		var secondclass = $(divelement).attr('class').split(' ').slice(-1); 
		
		if(secondclass != "no_login"){
			$.ajax({
				type: "POST",
				url: "/admin/ajax_toogle_manufacturer_status.php",
				data: "her_id=" +her_id,
				success: function(msg){
					/* get the new status from the returned data*/
					//alert(msg);
					if(msg == "active" || msg == "inactive"){
						/* remove all classes to reveal default state (eg. animation)*/
						$(divelement).removeClass();
						/* add new classes */
						$(divelement).addClass("statusimg ");
						$(divelement).addClass(msg);
					}else{
						alert(msg);
						$(divelement).addClass("statusimg ");
					}
				}
			});
		}
	});
	
	// toogle product status
	$('#products').find('div.statusimg').click(function() {
		var divelement = this;
		var ver_id = divelement.id;
		var secondclass = $(divelement).attr('class').split(' ').slice(-1); 
		
			$.ajax({
				type: "POST",
				url: "/admin/ajax_toogle_product_status.php",
				data: "ver_id=" +ver_id,
				success: function(msg){
					/* get the new status from the returned data*/
					//alert(msg);
					if(msg == "active" || msg == "inactive"){
						/* remove all classes to reveal default state (eg. animation)*/
						$(divelement).removeClass();
						/* add new classes */
						$(divelement).addClass("statusimg ");
						$(divelement).addClass(msg);
					}else{
						alert(msg);
						$(divelement).addClass("statusimg ");
					}
				}
			});
	});
	
	
	// ADMIN CATEGORIES HANDLING
	if ( $("#edit_categories").length > 0 ) {
		// close all by default
		$('div.edit_box').hide();
		
		// click on image to edit
		$('.open_edit_box').click(function(){
			var prg_id = this.id;
			// close all
			$('div.edit_box').hide();
			// open requested one
			$('#box_'+prg_id).show();
			
			// write old value to new field
			var current_name = $('span#name_'+prg_id).html();
			$("#feld_"+prg_id).val(current_name);
		});
		
		// click on submit button
		$('.savebutton').click(function(){
			var prg_id = this.id;
			var prg_name = $("#feld_"+prg_id).val();
			
			
			$.ajax({
				type: "POST",
				url: "/admin/ajax_update_category.php",
				data: "prg_id=" +prg_id+ "&prg_beschreibung=" +escape(prg_name),
				success: function(msg){
					//alert(msg);
					$('span#name_'+prg_id).text(msg);
				}
			});
		});
		
	}
	
	// Validate product upload form
	$("#ver_bildname").change(function () {
		var ext = $('#ver_bildname').val().split('.').pop().toLowerCase();
		var allow = new Array('jpg','jpeg');
		if(jQuery.inArray(ext, allow) == -1) {
		    //alert('Unerlaubtes Dateiformat!');
			if ( $("span.red").length == 0 ) {
				$("span.green").remove();
				$("#ver_bildname").after('<span class="red">Unerlaubtes Dateiformat!</span>');
				$('#ver_bildname').val("");
			}
		}else{
			if ( $("span.red").length > 0 ) {
				$("span.red").remove();
				$("#ver_bildname").after('<span class="green">Dateiformat ok!</span>');
			}
		}
	});
	
        

	
	 /****************************************************************************************************************/
	// PASSWORD STRENGHT
		var shortPass 	= 'Mindestens 6 Zeichen'
		var longPass 	= 'Maximal 79 Zeichen'
		var badPass 	= ''
		var goodPass 	= ''
		var strongPass 	= ''
		function passwordStrength(password)
		{
		    score = 0 
		    if (password.length < 6 ) { return '<div class="graph"><span id="gesamt" class="bar minifont minifont" style="width: 100%; solid #000000; background:none;">'+shortPass+'</span></div>' }
			if (password.length > 79 ) { return '<div class="graph"><span id="gesamt" class="bar minifont" style="width: 100%; solid #000000; background:none;">'+longPass+'</span></div>' }
		    score += password.length * 6
		    score += ( checkRepetition(1,password).length - password.length ) * 1
		    score += ( checkRepetition(2,password).length - password.length ) * 1
		    score += ( checkRepetition(3,password).length - password.length ) * 1
		    score += ( checkRepetition(4,password).length - password.length ) * 1
		    if (password.match(/(.*[0-9].*[0-9].*[0-9])/))  score += 5 
		    if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) score += 5 
		    if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))  score += 5 
		    if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))  score += 10 
		    if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/))  score += 10 
		    if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/))  score += 10 
		    if (password.match(/^\w+$/) || password.match(/^\d+$/) )  score -= 10 
		    if ( score < 0 )  score = 0 
		    if ( score > 100 )  score = 100 
		    if (score < 45 )  return '<div class="graph"><span id="gesamt" class="bar minifont" style="width: '+score+'%; solid #000000;">'+badPass+'</span></div>'
		    if (score < 80 )  return '<div class="graph"><span id="gesamt" class="bar minifont" style="width: '+score+'%; solid #000000;">'+goodPass+'</span></div>'
		    return '<div class="graph"><span id="gesamt" class="bar minifont" style="width: '+score+'%; solid #000000;">'+strongPass+'</span></div>'
		}
		
		function checkRepetition(pLen,str) {
		    res = ""
		    for ( i=0; i<str.length ; i++ ) {
		        repeated=true
		        for (j=0;j < pLen && (j+i+pLen) < str.length;j++)
		            repeated=repeated && (str.charAt(j+i)==str.charAt(j+i+pLen))
		        if (j<pLen) repeated=false
		        if (repeated) {
		            i+=pLen-1
		            repeated=false
		        }
		        else {
		            res+=str.charAt(i)
		        }
		    }
		    return res
		}
		
		$('#password1').keyup(function(){ $('#result').html(passwordStrength($('#password1').val())) });
		
		
	/****************************************************************************************************************/
	// OTHER
		// Admin => Products => Serach for Manufacturer
		$("#search_for_manufact").change(function(){
			if ($(this).val().length > 0) {
				$("#admin_search_products").submit();
            }else{
				// empty entry chosen
				window.location.href = ("index.php?action=products");
			}
     	});
		
		// Admin => Products => Serach for artcle
		$("#search_for_artnum").change(function(){
			var ver_id = $(this).val();
			var her_id = $("#search_for_manufact").val();
			if (ver_id.length > 0) {
				// ?action=products&function=list&sub=edit&ver_id=147
				var newurl = "index.php?action=products&function=list&sub=edit&ver_id=" + ver_id + "&search_manufact=" + her_id + "&search_artnum=" + ver_id;
					window.location.href = (newurl);
			}else{
				// empty entry chosen
				window.location.href = ("index.php?action=products");
			}
		});
});
