/**
 * jquery_api_quote.js - JavaScript Functions.
 * @package jquery_api_quote.js
 * @copyright 2005 - 2008 OSD
 * Functions for quote module
*/

	$(document).ready(function(){		
		$("#featured").tabs({fx:{opacity: "toggle"}}).tabs("rotate", 5000, true); 		
		$('#target').blur(function() {check_for_duplicate_email();});

		/*Portfolio Auto Filter*/
		var filtered = false;
		//check if there are any sectors checked.
		$(".sectors_checkbox").each(function(){if($(this).attr('checked') == true){filtered = true;}});
		//check if there are any services checked.
		$(".services_checkbox").each(function(){if($(this).attr('checked') == true){filtered = true;}});
		//if there was something checked, update the portfolio.
		if(filtered == true){update_portfolio_list();}
		
		//applies a filter to the list
		$("#portfolio_filter_btn").click(function(){update_portfolio_list();});
		//applies a filter to the list
		$(".portfolio_back_btn").click(function(){update_portfolio_list();});

		//toggle the selection of all or none of the sectors & services
		$('#pf_check_all').click(function(){
			$('.services_checkbox, .sectors_checkbox').attr("checked",$(this).attr('checked'));			
			//after all/none of the types are selected update the session via ajax
			update_portfolio_selected_types('sectors');
			update_portfolio_selected_types('services');
		});

		/*client login form positioning and effects*/
		if($('#client_login').length > 0){
			//if client login we are in front end
			
			$('#client_login_form').hide();
			var client_login_pos = $('#client_login').position();
			var client_login_top = client_login_pos.bottom;
			var client_login_left = client_login_pos.left;		
			$('#client_login_form').css({'top':client_login_top,'left':client_login_left});	
		
			//show/hide form
			$('#client_login,#client_login_cancel_btn').click(function(){
				$('#client_login_form').toggle();
				$('#client_login_form span').hide();
				$('#client_username').val("");
				$('#client_password').val("");
			});
	
			//login msg
			$('#client_login_btn').click(function(){
				var client_error = false;
				var username = $('#client_username').val();
				var password = $('#client_password').val();
				//reset error messages
				$('#client_login_form span').hide();
				//validation checks
				if(username == "" || username == null){
					$('#client_bad_user').show();
					client_error = true;
				}
				if(password == "" || password == null){
					$('#client_bad_pass').show();
					client_error = true;
				}
				//validation action
				if(client_error == false){$('#client_bad_login').show();}
				else{alert("Error:\n"+client_error_msg);}
			});
		
		
		
			//portfolio: Set selected sectors and services
			if(selected_sectors != 0 || selected_services != 0){
				//alert('sectors:'+selected_sectors+'\nservices:'+selected_services);
				
				if(selected_sectors != 0){
					var sel_sectors_array 	= selected_sectors.split('-');
					$(".sectors_checkbox").each(function(){
						var checkbox_val = $(this).val();
						if(isValueInArray(sel_sectors_array,checkbox_val)){
							$(this).attr('checked',true);
						}
					});
					
				}
				else{
					$(".sectors_checkbox").each(function(){$(this).attr('checked',false);});
				}
				
				if(selected_services != 0){
					var sel_services_array 	= selected_services.split('-');
					$(".services_checkbox").each(function(){
						var checkbox_val = $(this).val();
						if(isValueInArray(sel_services_array,checkbox_val)){
							$(this).attr('checked',true);
						}
					});
				}
				else{
					$(".services_checkbox").each(function(){$(this).attr('checked',false);});
				}
				
				//if all checkboxes are checked update the all checkbox 
				//(Logic: if checkbox count == checkbox:checked count)
				if(($(".services_checkbox").length == $(".services_checkbox:checked").length) && ($(".sectors_checkbox").length == $(".sectors_checkbox:checked").length)){
					$('#pf_check_all').attr('checked',true);
				}
				else{
					$('#pf_check_all').attr('checked',false);
				}
			}
			
			//add click event to all sector check boxes
			$(".sectors_checkbox").click(function(){update_portfolio_selected_types('sectors');});		
			//add click event to all service check boxes
			$(".services_checkbox").click(function(){update_portfolio_selected_types('services');});
		}
		
	});//end (document).ready()
	
/**
 * @desc get the selected values from a given type
 * @param type
 * @return
 */	
function update_portfolio_selected_types(type){
	//alert('update');
	var selected_string = "";
	var selected_array = new Array();
	var checkbox_selector = ((type == 'services')? $(".services_checkbox:checked"):$(".sectors_checkbox:checked")); 
	//when one is clicked loop through all and find the selected ones
	
		if(checkbox_selector.length > 0 ){
			checkbox_selector.each(function(){
				//alert($(this).attr('checked'));
				selected_array.push($(this).val());						
			});	
			selected_string = ((selected_array.length >0)? selected_array.join('-'):"");
		}
		else{
			selected_string = "";
		}
	
	//alert(type+":"+selected_string);
	update_selected_sectors_and_services(type,selected_string);
	//if all checkboxes are checked update the all checkbox 
	//(Logic: if checkbox count == checkbox:checked count)
	if(($(".services_checkbox").length == $(".services_checkbox:checked").length) && ($(".sectors_checkbox").length == $(".sectors_checkbox:checked").length)){
		$('#pf_check_all').attr('checked',true);
	}
	else{
		$('#pf_check_all').attr('checked',false);
	}
	return;
}


/**
 * @desc sets the selected sectors/services in the session
 * @param type is either 'sectors' or 'services'
 * @param is a '-' seperated of the selected id's
 * @return boolean
 */
function update_selected_sectors_and_services(type,data){
	//alert('data:'+data);
	var data_helper = "/osd_helpers/osd_set_selected_portfilio_types.php";		
		$.ajax({
			type: "POST",
			url: data_helper,
			cache: false,
			data: {	
				selected_type: type,			
				selected_data: data			
			},
			success: function(task_data) {			
				//alert('SUCCESS: selected'+type+":"+data+"\n\n"+task_data);
			},
			fail: function(task_data){
				alert('Portfolio '+type+'not selected');
			}
		}); // ajax	
}

/**
 * @desc updates the portfolio list according to the selected checkboxes
 * @return
 */
function update_portfolio_list(){
	var data_helper = "/osd_helpers/osd_get_portfolios.php";
	var selected_sectors = [];  
	var selected_services = [];	
	var show_archived = false;
	//populate the Selected sectors array.
    $('#portfolio_sectors input:checked').each(function() {selected_sectors.push($(this).val());});		
	//populate the Selected services array.	  
    $('#portfolio_services input:checked').each(function() {selected_services.push($(this).val());});	
    selected_sectors_string 	= selected_sectors.join(",");
    selected_services_string 	= selected_services.join(",");
    
    show_archived 				= $('#pf_show_archived').attr('checked');
    
    //alert("Sectors:\n"+selected_sectors_string+"\n\nServices:\n"+selected_services_string); 
	if(selected_sectors_string != "" || selected_services_string != ""){	
		$.ajax({
			type: "POST",
			url: data_helper,
			cache: false,
			data: {
				sectors: 		selected_sectors_string,	
				services: 		selected_services_string,	
				show_archived:	show_archived
			},
			success: function(task_data) {			
				//success - add element to the end of the list		
				if(task_data.search(/Error:/) == -1){
					//no error
					//alert(task_data);
					if(task_data != ""){					
						var return_html = "";
						//get the return string and turn it into an array of rows/records
						var rows = task_data.split('-#-');
						
						return_html += "<span id='portfolio_count'>("+rows.length+" Portfolios)</span>";
						//iterate over the rows and create html object to be placed in the page 					
						for(var i = 0; i < rows.length; i++){
							
							var row_item = rows[i].split("|");
							/* returned record index
							0 = id
							1 = title
							2 = tagline
							3 = image
							4 = url_slug
							5 = site_link
							*/				
						
							return_html += "<div class=\"pf_list_item\">\n";
							return_html += "<h4 class='pf_title_link'><a title='OSD Portfolio: "+row_item[1]+"' href='/portfolio/view/"+row_item[4]+"'>\n";
							return_html += row_item[1]+"</a></h4>\n";	
							return_html += "<a title='OSD Portfolio: "+row_item[1]+"' href='/portfolio/view/"+row_item[4]+"'>\n";
							return_html += "<img alt='"+row_item[1]+" preview image' title='OSD Portfolio: "+row_item[1]+" image' src='"+row_item[3]+"' style='width:208px;'>\n";
							return_html += "</a>\n";
							return_html += "<p class=\"pf_list_item_text\">"+row_item[2]+"</p> \n";							
							return_html += "<a class='view_portfolio_btn' title='OSD Portfolio: "+row_item[1]+"' href='/portfolio/view/"+row_item[4]+"'>View Portfolio</a>\n";
							return_html += "<br class=\"clear\" /> \n";
							return_html += "</div> \n\n";
							$('#pf_main_txt').hide();
							$('#portfolio_container').html(return_html);						
						}					
					}
					else{ 
						$('#portfolio_container').html("<font color='red' size='4'>Sorry, there are currently no portfolios under the selected sectors or services.</font>");
					}
				}		
				else{
					//error
					alert("Error:\n"+task_data);
				}
			},
			fail: function(task_data){
				alert('FAIL BIG TIME');
			}
			}); // ajax
	}
	else{
		//alert('Please select at least one service or sector from the menu on the left');
		window.location= "/portfolio";
		}
}

/** 
 * @param exclude_ids array of ids's already selected
 * @return html
 */
function update_portfolio_search(exclude_ids){
	var data_helper = "/osd_helpers/osd_get_portfolios_search.php";	
	
	if(exclude_ids != null){	
		$.ajax({
			type: "POST",
			url: data_helper,
			cache: false,
			data: {
			exclude_ids: selected_sectors_string			
		},
		success: function(task_data) {			
			//alert('SUCCESS:'+task_data);
		},
		fail: function(task_data){
			alert('Portfolio search ajax request failed!');
		}
		}); // ajax
	}
	else{alert('Please select at least one service or sector from the menu on the left');}
}



/**
 * @desc check to see if a value is in an arary
 * @return boolean
 */
function isValueInArray(arr, val) {
	inArray = false;
	for (i = 0; i < arr.length; i++)
		if (val == arr[i])
			inArray = true;
	return inArray;
}


