/*  SEARCH BOX CLEAR Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net)
  * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
  * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
  *
  * $LastChangedDate$
  * $Rev$
  *
  * Version 0.2
  *
  * Usage:
  *   $("input[name=q]")
  *      .val("Search")    // set an initial value if it doesn't already exist
  *      .clearonfocus();  // prepare the element for clearing on focus
  */
 jQuery.fn.clearonfocus = function() {
     return this
         .bind('focus', function() {
             // Set the default value if it isn't set
             if ( !this.defaultValue ) this.defaultValue = this.value;
             // Check to see if the value is different
             if ( this.defaultValue && this.defaultValue != this.value ) return;
             // It isn't, so remove the text from the input
             this.value = '';
         })
         .bind('blur', function() {
             // If the value is blank, return it to the defaultValue
             if ( this.value.match(/^\s*$/) )
                 this.value = this.defaultValue;
         });
 };

// Password strength meter
// This jQuery plugin is written by firas kassem [2007.04.05]
// Firas Kassem  phiras.wordpress.com || phiras at gmail {dot} com
// for more information : http://phiras.wordpress.com/2007/04/08/password-strength-meter-a-jquery-plugin/
// Modified by Adam Taylor

function passwordStrength(password, username)
{
	var shortPass = '<span class="password_short">Too short</span>'
	var commonPass = '<span class="password_common">Too common</span>'
	var lacksVariation = '<span class="password_lacks_variation">Not enough variation</span>'
	var badPass = 'Password strength: <span class="password_weak">Weak</span>'
	var goodPass = 'Password strength: <span class="password_medium">Medium</span>'
	var strongPass = 'Password strength: <span class="password_strong">Strong</span>'

	var score = 0

	//password < 8
	if (password.length < 8 ) { return shortPass }

	//password == username
	if (typeof(username)=='string' && password.toLowerCase()==username.toLowerCase()) return badPass

	//password is common
	if ($.inArray(password.toLowerCase(), common_passwords) > -1) return commonPass

	//password has variation
	character_types_used = 0;
	if (password.match(/([a-z])/))  character_types_used++
	if (password.match(/([A-Z])/))  character_types_used++
	if (password.match(/([0-9])/))  character_types_used++
	if (password.match(/([^a-zA-Z0-9])/))  character_types_used++
	if (character_types_used < 2) return lacksVariation

	//password length
	score += password.length * 4
	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

	//password has 3 numbers
	if (password.match(/(.*[0-9].*[0-9].*[0-9])/))  score += 5

	//password has 2 sybols
	if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) score += 5

	//password has Upper and Lower chars
	if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))  score += 10

	//password has number and chars
	if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))  score += 15
	//
	//password has number and symbol
	if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/))  score += 15

	//password has char and symbol
	if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/))  score += 15

	//password is just a nubers or chars
	if (password.match(/^\w+$/) || password.match(/^\d+$/) )  score -= 10

	//verifing 0 < score < 100

	if ( score < 0 )  score = 0
	if ( score > 100 )  score = 100

	if (score < 34 )  return badPass
	if (score < 68 )  return goodPass
	return strongPass
}

// checkRepetition(1,'aaaaaaabcbc')   = 'abcbc'
// checkRepetition(2,'aaaaaaabcbc')   = 'aabc'
// checkRepetition(2,'aaaaaaabcdbcd') = 'aabcd'

function checkRepetition(pLen,str)
{
	var 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
}

function verify_passwords_match()
{
	if ($('#confirm_new_password').val() == $('#new_password').val())
	{
		$('#password_match_status').removeClass('passwords_dont_match').addClass('passwords_match').html('Passwords match');
	}
	else
	{
		$('#password_match_status').removeClass('passwords_match').addClass('passwords_dont_match').html('Passwords do not match');
	}
}

function check_reset_password_form_submit_button()
{
	if ($('#new_password_strength').html().indexOf('Password strength:') == 0 && $('#password_match_status').html() == 'Passwords match')
	{
		$('#reset_password_form input[type="submit"]').removeAttr('disabled');
	}
	else
	{
		$('#reset_password_form input[type="submit"]').attr('disabled', 'disabled');
	}
}

function show_form(form_type)
{
	if (form_type == 'buyer_login')
	{
		$('#sidebarClientLoginFormContainer').hide();
		$('#sidebarBuyerLoginFormContainer').show();
		$('#sidebarClientLoginHeading').removeClass('active');
		$('#sidebarBuyerLoginHeading').addClass('active');
	}
	else if (form_type == 'client_login')
	{
		$('#sidebarBuyerLoginFormContainer').hide();
		$('#sidebarClientLoginFormContainer').show();
		$('#sidebarBuyerLoginHeading').removeClass('active');
		$('#sidebarClientLoginHeading').addClass('active');
	}
}

function check_client_report_download_links(CrmId)
{
	enable_download_links = true;

	$('form#form' + CrmId + ' .report_parameter input').each(function()
	{
		if ($.trim($(this).val()) == '' || ($(this).is(':radio') && $('form#form' + CrmId + ' input[name="' + $(this).attr('name') + '"]:checked').length < 1))
		{
			// enable_download_links = false;
			enable_download_links = true;
		}
	});

	if (enable_download_links == true)
	{
		$('#download_links' + CrmId).removeClass('disabled');
	}
	else
	{
		$('#download_links' + CrmId).addClass('disabled');
	}
}

$(document).ready(function(){
	$('#s').val("Category Search").clearonfocus();
		$('.sidebarLogin input[name="email"]').val("E-mail Address").clearonfocus();
			$('.sidebarLogin input[name="pass"]').val("Password").clearonfocus();

	if ($('#sidebarClientLoginFormContainer').length == 1)
	{
		$('.sidebarLogin').addClass('sidebarLoginJS').prepend('<div id="sidebarLoginTop"></div>');
		$('#sidebarLoginTop').css('width', $('.sidebarLogin').width() + 'px').css('height', ($('#sidebarBuyerLoginHeading').outerHeight() + 5) + 'px');
		$('#sidebarClientLoginHeading').insertAfter('#sidebarBuyerLoginHeading');

		var tab_width = Math.floor((($('.sidebarLogin').width() - (($('#sidebarBuyerLoginHeading').offset().left - $('.sidebarLogin').offset().left) * 7)) / 2));

		$('#sidebarBuyerLoginHeading, #sidebarClientLoginHeading').css('width', tab_width + 'px');

		$('.sidebarLogin h3').each(function()
		{
			$(this).html('<a href="#">' + $(this).html() + '</a>');
		});

		if ($('#sidebarClientLoginFormErrors').length == 1 || $('#client_logged_in').length == 1)
		{
			show_form('client_login');
		}
		else
		{
			show_form('buyer_login');
		}

		$('#sidebarBuyerLoginHeading a').click(function()
		{
			show_form('buyer_login');
			return false;
		});

		$('#sidebarClientLoginHeading a').click(function()
		{
			show_form('client_login');
			return false;
		});

		$('#sidebarClientLoginForm').submit(function()
		{
			$('#sidebarClientLoginForm input[name="email"]').val($.trim($('#sidebarClientLoginForm input[name="email"]').val()));

			var form_errors = [];

			if ($('#sidebarClientLoginForm input[name="email"]').val() == 'E-mail Address' || $('#sidebarClientLoginForm input[name="email"]').val() == '')
			{
				form_errors.push('You forgot to enter an e-mail address');
			}

			if ($('#sidebarClientLoginForm input[name="pass"]').val() == 'Password' || $('#sidebarClientLoginForm input[name="pass"]').val() == '')
			{
				form_errors.push('You forgot to enter a password');
			}

			var total_form_errors = form_errors.length;

			if (total_form_errors > 0)
			{
				// At least one error was found with the form.

				var form_error_html = '<p>Please correct the following error';

				if (total_form_errors > 1)
				{
					form_error_html += 's';
				}

				form_error_html += ' and then try again.</p><ul>';

				$.each(form_errors, function(index, value)
				{
					form_error_html += '<li>' + value + '</li>';
				});

				form_error_html += '</ul>';

				if ($('#sidebarClientLoginFormErrors').length < 1)
				{
					$('#sidebarClientLoginFormContainer').prepend('<div id="sidebarClientLoginFormErrors"></div>');
				}

				$('#sidebarClientLoginFormErrors').html(form_error_html);
				return false;
			}
			else
			{
				// No errors were found with the form.

				// Disable the form's submit button so that the user is unable to
				// continuously click it.

				$('#sidebarClientLoginForm input[type="submit"]').attr('disabled', 'disabled');
			}
		});
	}

	$('[title]').qtip(
	{
		position:
		{
			at: 'top center',
			my: 'bottom center'
		},
		style:
		{
			classes: 'ui-tooltip-shadow ui-tooltip-dark'
		}
	});

	if ($('.clientReportsTable').length > 0)
	{
		$('.table_cell_download').each(function()
		{
			if ($(this).find('form').length == 1)
			{
				if ($(this).find('select[name="format"] option[value="excel"]').length == 1)
				{
					var excel = true;
				}
				else
				{
					var excel = false;
				}

				if ($(this).find('select[name="format"] option[value="PDF"]').length == 1)
				{
					var PDF = true;
				}
				else
				{
					var PDF = false;
				}

				var download_links_html = '<td class="table_cell_download_links"><p id=\"download_links' + $(this).find('form').attr('id').slice(-36) + '\" class=\"download_links\">';

				if (PDF == true)
				{
					download_links_html += '<a href="#" class="PDF_download"><span>PDF</span></a>';

					if (excel == true)
					{
						download_links_html += '<span style="display: block; width: 5px; height: 5px;"></span>';
					}
				}

				if (excel == true)
				{
					download_links_html += '<a href="#" class="excel_download"><span>Excel</span></a>';
				}

				download_links_html += '</p><div style="clear: both;"></div></td>';

				$(this).after(download_links_html);
				$(this).find('select[name="format"]').parent().remove();

				check_client_report_download_links($(this).find('form').attr('id').slice(-36));
			}
			else
			{
				$(this).after('<td class="table_cell_download_links"></td>');
			}
		});

		$('.table_cell_download_links .download_links a').click(function()
		{
			if ($(this).parent().hasClass('disabled'))
			{
				alert('You must complete the form before downloading this report.');
			}
			else
			{
				if ($('form#form' + $(this).parent().attr('id').slice(-36) + ' input#format' + $(this).parent().attr('id').slice(-36)).length < 1)
				{
					$('form#form' + $(this).parent().attr('id').slice(-36)).append('<input type="hidden" name="format" id="format' + $(this).parent().attr('id').slice(-36) + '" />');
				}

				if ($(this).hasClass('excel_download'))
				{
					$('form#form' + $(this).parent().attr('id').slice(-36) + ' input#format' + $(this).parent().attr('id').slice(-36)).attr('value', 'excel');
				}
				else
				{
					$('form#form' + $(this).parent().attr('id').slice(-36) + ' input#format' + $(this).parent().attr('id').slice(-36)).attr('value', 'PDF');
				}

				$('form#form' + $(this).parent().attr('id').slice(-36)).submit();
			}

			return false;
		});

		$('.table_cell_download input[type="text"]').bind('keyup change', function()
		{
			check_client_report_download_links($(this).attr('id').slice(-36));
		}).on('focus', function()
		{
			CrmId = $(this).attr('id').slice(-36);
			timer = setInterval('check_client_report_download_links(CrmId)', 100);
		}).on('blur', function()
		{
			clearInterval(timer);
		});

		$('.table_cell_download :radio').change(function()
		{
			check_client_report_download_links($(this).attr('id').slice(-36));
		});

		$('.clientReportsTable .date').attr('readonly', 'readonly').datepicker(
		{
			dateFormat: 'yy-mm-dd',
			showButtonPanel: true,
			onClose: function()
			{
				check_client_report_download_links($(this).attr('id').slice(-36));
			}
		});

		$('.table_cell_name_description').css('width', '40%');
		$('.table_cell_download').css('width', '50%');
		$('.table_cell_download_links').css('width', '10%');
	}

	if ($('#reset_password_form').length > 0)
	{
		$('#reset_password_form input[type="submit"]').attr('disabled', 'disabled');
		$('#new_password').after('<span id="new_password_strength"></span>');
		$('#confirm_new_password').after('<span id="password_match_status"></span>');

		$('#new_password').bind('keyup blur', function()
		{
			$('#new_password_strength').html(passwordStrength($(this).val()));

			if ($('#password_match_status').html() != '')
			{
				verify_passwords_match();
			}

			check_reset_password_form_submit_button();
		});

		$('#confirm_new_password').bind('keyup blur', function()
		{
			if ($(this).val() != '')
			{
				verify_passwords_match();
			}
			else
			{
				$('#password_match_status').removeClass('passwords_match').removeClass('passwords_dont_match').html('');
			}

			check_reset_password_form_submit_button();
		});
	}
});


/* DROP DOWN MENU - The following 2 items call the dropdown menu behaviors. First up is a function that expands the dropdown to the largest sub item. Must come first. After that is the SuperFish menu call itself. */
$(document).ready(function(){ 
        $("ul.sf-menu").supersubs({ 
            minWidth:    9,   // minimum width of sub-menus in em units 
            maxWidth:    27,   // maximum width of sub-menus in em units 
            extraWidth:  1     // extra width can ensure lines don't sometimes turn over 
                               // due to slight rounding differences and font-family 
        }).superfish();  // call supersubs first, then superfish, so that subs are 
                         // not display:none when measuring. Call before initialising 
                         // containing tabs for same reason. 
    }); 

jQuery(function(){
	jQuery('ul.sf-menu').superfish();
});


/* IMAGE SWAPS  example of usage: give img the .buttonswap class and make sure to get the on (mouse on) and off (mouse off) */
$(document).ready(function(){
	$(".buttonSwap").hover(
	 function()
	 {this.src = this.src.replace("_off","_on");},
	 function()
	 {this.src = this.src.replace("_on","_off");}
	);
});


/* TABLE ZEBRA STRIPE */
$(document).ready(function(){
	$(".equipmentTable tr:nth-child(even)").addClass("alt");
});



/* PRODUCT LIST ZEBRA STRIPE */
$(document).ready(function(){
	$(".productList li:nth-child(even)").addClass("alt");
});


/* TRANSLATION CODE */
$(document).ready(function(){ //when DOM is ready 
 
  $.translate(function(){  //when the Google Language API is loaded 
   
	function translateTo( destLang ){ //this can be declared in the global scope too if you need it somewhere else 
        $('body').translate( 'english', destLang, {   //translate from english to the selected language 
          not: '#footer',  //do not translate this item
          fromOriginal:true   //always translate from english (even after the page has been translated) 
           }); 
    }  
     
	$('#transMap')
      .find('area')
      .click(function(){
         var lang = $(this).attr('id');
         translateTo( lang );
         $.cookie('destLang', lang );
           this.blur();
  			return false;
     })
     
   
    var destLang = $.cookie('destLang'); //get previously translated language 
    if( destLang )  //if it was set then 
        translateTo( destLang ); 

 
  }); //end of Google Language API loaded 
   
}) //end of DOM ready



/* PRODUCT TABLE CODE */
$(function() {
	/* hide items to be shown only when hovered over or toggled*/
	$('.pPictureStrip,.pNotes,.pAdditionalInfo,.pTextOverRun').hide();  

	$('.pWrapper').hover(
	function() {
	$(this).find('.pStatWrapper > *, .pDescWrapper > .pAdditionalInfo').show();
	$(this).css("border-color","#d15d00")
	},
	function() {
	$(this).find('.pDescWrapper > .pAdditionalInfo, .pPictureStrip,.pNotes,.pTextOverRun').hide();
	$(this).find('.moreDesc').show();
	$(this).css("border-color","#e4e4e4 #FAFAFA")
	;
	});
	
	$('.moreDesc').click (function() {
		$(this).parent().parent().next().toggle();
		$(this).hide()
		return false; 
	});
	
      $('.morePhotos').click (function() {
         $(this).parent().parent().parent().parent().find('.pPictureStrip').toggle();
         return false; 
        }); 
	
	$('.moreInfo').click (function() {
		$(this).parents().find('.pNotes').toggle();
		return false; 
	});
	
});


/* LIGHTBOX CODE */
$(document).ready(function(){
	$(".lightBox").lightbox();
			
});


/* OVERLAY CODE */
$(document).ready(function(){
$('.moreDescs').click (function() {
			var myOverlay = (new documentOverlay())
        .css({
            background: 'black',
            opacity: 0.5,
            filter: 'alpha(opacity=50)'
        })
        .on('click',function(){
            myOverlay.remove();
        })
        .init();
        });
});

/* HOMEPAGE SLIDESHOW CODE */
$(document).ready(function(){
$('#slideshowFPO').cycle({ 
    timeout:  6000,
    pause:  1,
    speed:  1500});
});

