$(function() {
	
	/* Start Feedback Widget -PD */
	if(!jQuery.isFunction(jQuery.fn.colorbox)){
		$.getScript("../js/jquery.colorbox-min.js");
	}
	if(!$("#home").hasClass("new2011")){
		$('body').prepend('<a id="feedback-widget" href="../l/feedback-widget.php" style="z-index:9999;display:block;width:40px;height:140px;background:url(../images/feedback_icon_sprite.png) no-repeat 0 0 transparent;position:fixed;top:120px;right:-2px;font-size:0px;">Feedback</a>');
		$("#feedback-widget").mouseover(function(){$(this).css('background-position','-40px top')}).mouseout(function(){$(this).css('background-position','0px top')});
		$('a#feedback-widget').colorbox();
	}
	//$('#feedback-widget').hide(0);
	$('a#link-feedback').colorbox();
	/* End Feedback Widget -PD */
		
	//Homepage Gigya Login For Validate

	if( jQuery.isFunction(jQuery.fn.validate) ){ //Check to see if validate() exists
	    //alert("1");
	    $("#loginform-2").validate({ 
	    	rules: { 
	    		form_login: {
		    		required: true,
		          	email: true 
	    		}, 
	    		form_password: {
	    			required: true
	       		} 
	        },
	        messages: { 
	          'form_login': "Enter an email like \'name@email.com\'",
	          'form_password': "Password is required"
	        },
			errorElement: "div",
			errorClass: "ErrMsg",
			highlight: function(element, errorClass) {
				if($(element).attr("name") == 'terms') {
				}else{
					$(element).next().removeClass('CorrectFld');
					$(element).next().addClass('WrongFld');
					$(element).next().text('X');
					$(element).parent().removeClass('valid');
					$(element).parent().addClass('error');
					$(element).prev().removeClass('FldLbl');
					$(element).prev().addClass('ErrLbl');
				}
			},
			errorPlacement: function(error, element) {
				element.parent().removeClass('valid');
				element.parent().addClass('error');
				if(element.attr("name") == 'terms') {
					error.attr("id", "user-terms");
				}
				element.parent().find('div.ErrMsg').remove();
				var errText = error.text();
				if(errText){
					if(element.attr("name") == 'terms') {
						error.insertAfter(element.next());
					} else {
						element.next().removeClass('CorrectFld');
						element.next().addClass('WrongFld');
						element.next().text('X');
						error.insertAfter(element.next());
					}
				}else{
					error.append('&nbsp;');
					if(element.attr("name") == 'terms') {
						error.insertAfter(element.next());
					} else {
						element.next().removeClass('CorrectFld');
						element.next().addClass('WrongFld');
						element.next().text('X');
						error.insertAfter(element.next());
					}
				}
			},
			error: function(label) {
				alert('here');
			},
			success: function(label) {
	 			label.text("");
	 			label.append("&nbsp;");
	 			label.parent().addClass("valid");
	 			label.parent().removeClass("error");
			
				if(label.prev().prev().attr("name") == 'terms') {
				} else {	
					label.prev().text('OK');
					label.prev().removeClass('WrongFld');
					label.prev().addClass('CorrectFld');
					label.prev().prev().prev().removeClass('ErrLbl');
					label.prev().prev().prev().addClass('FldLbl');
					$(".login-err").slideUp(500,function(){$(this).remove();});					
				}
			},
			
			submitHandler: function(form) {
				/*
				var callUrl = $(form).attr('action');
				$.ajax({
					url: callUrl,
					dataType: 'jsonp',
					success: function(data){
						alert(data);
					},
					error: function(){
						alert('error');
					}
				});
				*/
				
				//alert("SUCCESS");
				
				$(form).ajaxSubmit({
					/*
					beforeSubmit: function(form){
						var 
					},
					*/
					error: function(data){
						alert('Error:' + data);
					},
					success: function(data){
						var data = $.parseJSON(data);
						if(data.result == false){
							var errorAlertMsg = 'Wrong password';
							$(form).find("input").next().removeClass('CorrectFld')
							$(form).find("input").next().addClass('WrongFld');
							$(form).find("input").next().text('X');
							$(form).find("input").parent().removeClass('valid');
							$(form).find("input").parent().addClass('error');
							$(form).find("input").prev().removeClass('FldLbl');
							$(form).find("input").prev().addClass('ErrLbl');
							$("#modal-login-list").prepend('<li class="login-err" style="background-color:#f5e5e5;padding:8px 10px 5px 10px;border:2px solid #990000;color:#990000;margin-bottom:10px;display:none;">Wrong Credentials. Please try again.</li>');
							$("#modal-login-list .login-err").slideDown(500);
							//.after('<span style="color:red;">' + errorAlertMsg + '</span>');
							//alert("Wrong Password");
						}
						else{
							window.location.href = '/l/myoffers.php';
						}
					}
				});
				
				//form.submit();
			}
	    });
	} //END IF
	
	if( jQuery.isFunction(jQuery.fn.validate) ){ //Check to see if validate() exists
	    $("#link-accounts").validate({ 
	    	rules: { 
	    		form_login: {
		    		required: true,
		          	email: true 
	    		}, 
	    		form_password: {
	    			required: true
	       		} 
	        },
	        messages: { 
	          'form_login': "Enter an email like \'name@email.com\'",
	          'form_password': "Password is required"
	        },
			errorElement: "div",
			errorClass: "ErrMsg",
			highlight: function(element, errorClass) {
				if($(element).attr("name") == 'terms') {
				}else{
					$(element).next().removeClass('CorrectFld');
					$(element).next().addClass('WrongFld');
					$(element).next().text('X');
					$(element).parent("li").removeClass('valid');
					$(element).parents("li").addClass('error');
					$(element).prev().removeClass('FldLbl');
					$(element).prev().addClass('ErrLbl');
				}
			},
			errorPlacement: function(error, element) {
				element.parents("li").removeClass('valid');
				element.parents("li").addClass('error');
				if(element.attr("name") == 'terms') {
					error.attr("id", "user-terms");
				}
				element.parent().find('div.ErrMsg').remove();
				var errText = error.text();
				if(errText){
					if(element.attr("name") == 'terms') {
						error.insertAfter(element.next());
					} else {
						element.next().removeClass('CorrectFld');
						element.next().addClass('WrongFld');
						element.next().text('X');
						error.insertAfter(element.next());
					}
				}else{
					error.append('&nbsp;');
					if(element.attr("name") == 'terms') {
						error.insertAfter(element.next());
					} else {
						element.next().removeClass('CorrectFld');
						element.next().addClass('WrongFld');
						element.next().text('X');
						error.insertAfter(element.next());
					}
				}
			},
			error: function(label) {
				alert('here');
			},
			success: function(label) {
	 			label.text("");
	 			label.append("&nbsp;");
	 			label.parents("li").addClass("valid");
	 			label.parents("li").removeClass("error");
			
				if(label.prev().prev().attr("name") == 'terms') {
				} else {	
					label.prev().text('OK');
					label.prev().removeClass('WrongFld');
					label.prev().addClass('CorrectFld');
					label.prev().prev().prev().removeClass('ErrLbl');
					label.prev().prev().prev().addClass('FldLbl');
					$(".login-err").slideUp(500,function(){$(this).remove();});
				}
			},
			submitHandler: function(form) {
				//alert("SUCCESS");
				$(form).ajaxSubmit({
					error: function(data){
						//console.log('Error: <br /><br />' + data);
					},
					success: function(data){
						var data = $.parseJSON(data);
						if(data.result == false){
							var errorAlertMsg = 'Wrong password';
							$(form).find("input").next().removeClass('CorrectFld')
							$(form).find("input").next().addClass('WrongFld');
							$(form).find("input").next().text('X');
							$(form).find("input").parents("li").removeClass('valid');
							$(form).find("input").parents("li").addClass('error');
							$(form).find("input").prev().removeClass('FldLbl');
							$(form).find("input").prev().addClass('ErrLbl');
							$("#modal-link-accounts-list").prepend('<li class="login-err" style="color:#990000;margin-bottom:10px;display:none;">Wrong Credentials. Please try again.</li>');
							$("#modal-link-accounts-list .login-err").slideDown(500);
							//.after('<span style="color:red;">' + errorAlertMsg + '</span>');
							//alert("Wrong Password");
						}
						else{
							window.location.href = '/l/myoffers.php';
						}
					}				
				});
				//form.submit();
			}
	    });
	}//END IF
	
	//Homepage Social/Login modal window -PD
	$("#gigya-login").colorbox({
		inline:true,
		fixed:true,
		opacity:0,
		scrolling:false,
		href: "#gigya-login-modal"
	}, function(){
		//Callback if needed
	});
	
	//Link accounts modal
	$("#launch-link-accnt-modal").colorbox({
		inline:true,
		fixed:true,
		opacity:0,
		scrolling:false,
		href: "#gigya-link-accnt-modal"
	}, function(){
		//Callback if needed
	});
	
/*	
	function showAddressError(){
		$(".box-form .input-container").prepend("<label id='address-error' class='font-c55 error' style='display: none;'>Email address already exits</label>");
		$("#address-error").fadeIn(1000);
	};

	$('#ajaxregisteration').ajaxForm({error: showAddressError});
	*/

/*	
	$('#email-field').focus( function(){
		$('#error-field').html("");
		$('#email-field').html("");
	  }			
	);
*/
	$("#popupcontinue").click(function(){
		   $("#cboxOverlay").trigger("click");
		});

    if( jQuery.isFunction(jQuery.fn.ajaxForm) ){ //Check to see if validate() exists
        //alert("sadfsdfds");
        $('#ajaxregisteration').ajaxForm({
            beforeSubmit: function(){
                if(window.globalVariable === false){
                    return false;
                }
                $("#welcome .signup-box .box-head3 .checkbox").removeAttr("disabled");
                //console.log(".box-head3");
            },
            success: function (data){
                d = $.parseJSON(data);
                if(d.result == 1){
                    $('#error-field').text(d.data).show();
                } else {                    
                    document.location.href = d.data;
                }    
            },
            error: function(data){
                alert(data);
            }
        });
    }
	
    if( jQuery.isFunction(jQuery.fn.ajaxForm) ){ //Check to see if validate() exists
        $('#ajaxregistrationGiftcard').ajaxForm({
            beforeSubmit: function(){
                if(window.globalVariable === false){
                    return false;
                }
                $("#welcome .signup-box .box-head3 .checkbox").removeAttr("disabled");
                //console.log(".box-head3");
            },
            success: function (data){
                d = $.parseJSON(data);
                if(d.result == 1){
					$('#email-field').val(d.data).addClass('error');
                } else {                    
                    document.location.href = d.data;
                }    
            },
            error: function(data){
                alert(data);
            }
        });
    }
    
    /*	
	$('#submit-signup').click( function(){
		    if ($('#email-field') == ""){
		    	$('#error-field').text("Please enter email").show().addClass('error');
		    } else {
		    	//validate email
		    	var validEmail = true;
		    	
		    	if(validEmail == true ){
		    		
		       }
		    } //else 
		}//function
    );
  */  
	/*
    $('#ajaxhplogin').ajaxForm({success: function(data) {
                                        d = $.parseJSON(data);
                                        if (d['result'] == true) {
                                            document.location.href = "/l/myoffers.php";
                                        } else {
                                            alert ("username/password mismatch");
                                        }
                                        
                                       }, 
                                    failure: function(data) {
                                        alert ("Issue logging into the system: " + data);
                                    }}); 

        $('#nav > li').hover(function() {
		$('#header').css('z-index', 20);
		$('#main').css('z-index', 10);
		$(this).find('a:first').toggleClass('hover');
		var wid = $(this).width();
		$(this).find('ul').css('width', wid).stop(true,true).slideToggle();
	});
	
        
    */    
        
	$('.blink').live('focus', function() {
		if(this.id != 'email-field'){
				if(this.value == this.title) {
					this.value = ''
				}
				if($(this).parents('.field-container').length) {
					$(this).parents('.field-container').addClass('focus');
				} else {
					$(this).addClass('focus');
				}
		}
		else{
			if(this.value == this.title) {
				this.value = ''
			}
			if($(this).parents('.field-container').length) {
				$(this).parents('.field-container').addClass('email-field-focus');
			} else {
				$(this).addClass('email-field-focus');
			}
		}
	})
	.live('blur', function() {
		if(this.value == '') {
			this.value = this.title;
			if($(this).parents('.input-container').length) {
				$(this).parents('.input-container').find('label').show();
			}
		}
		if($(this).parents('.field-container').length) {
			$(this).parents('.field-container').removeClass('focus');
			$(this).parents('.field-container').removeClass('email-field-focus');
			$(this).parents('.field-container').find('.autosuggest').hide();
			if(this.value == this.title) {
				$(this).parents('.field-container').find('.clear').hide();
			}
		} else {
			$(this).removeClass('focus');
			$(this).removeClass('email-field-focus');
		}
	})
	.keyup(function() {
		autoSuggest($(this).val());
	});
	
	$('.input-container label').click(function() {
		$(this).parent().find('.blink').focus();
		$(this).hide();
	});
	
	$('#edit-username').keyup(function() {
		$('.username-info .blue').text($(this).val());
	});
	
	$('.clear').click(function() {
		$(this).parents('.field-container').find('.autosuggest').hide().find('.loader').show().next().hide().next().hide();
		window.setTimeout(function() {
			$('.field-container .clear').hide();
			$('.field-container .blink').val($('.field-container .blink').attr('title'));
			$('.card-buttons .pressed').removeClass('pressed');
		}, 50);
	});
	
	$('.card-buttons a').click(function() {
		var txt = $(this).find('img').attr('alt');
		$('.field-container .blink').val(txt).focus();
		$(this).addClass('pressed').siblings('.pressed').removeClass('pressed');
		autoSuggest(txt);
		return false;
	});
	
	$('.faq li > a').click(function() {
		$('.faq .open').removeClass('open').next().hide();
		$(this).toggleClass('open').next().toggle();
		return false;
	});
	
	$('.faq .more').bt({
	    fill: '#3a3a3a',
	    width : '204px',
		padding : '8px',
		positions : ['top'],
		spikeLength: 5,
		strokeWidth : '0',
		cornerRadius : 4,
		shadow : false
	});
	
	$('.card-buttons a img').bt({
	    fill: '#3a3a3a',
	    width : 'auto',
		padding : '8px',
		positions : ['top'],
		spikeLength: 5,
		strokeWidth : '0',
		cornerRadius : 4,
		shadow : false,
		cssClass: 'tt'
	});
	
	$('.btn-offers, .btn-savings').hover(function() {
		$('#header').css('z-index', 10);
		$('#main').css('z-index', 20).find('.shell').css('overflow', 'visible');
	});
	
	$('.circ-info, .ico-help').bt({
		fill: '#f6f6f6',
		width: '180px',
		padding: '8px',
		positions: ['top'],
		spikeLength: 13,
		spikeGirth: 22,
		strokeWidth : '1',
		strokeStyle: "#c1c1c1",
		cornerRadius : 5,
  		wrapperzIndex: 9997,
		shadow : true,
		cssClass: 'tt-grey'
	});
	
	$('.ico-help2').bt({
		fill: '#f6f6f6',
		width: '180px',
		padding: '8px',
		positions: ['right'],
		spikeLength: 13,
		spikeGirth: 22,
		strokeWidth : '1',
		strokeStyle: "#c1c1c1",
		cornerRadius : 5,
  		wrapperzIndex: 9997,
		shadow : true,
		cssClass: 'tt-grey'
	})
	
	$('a[class*="colorbox"]').colorbox();
	
	$('.claim-form .checkbox').change(function() {
		if($(this).is(':checked') == false) {
			$('.claim-form p.red').css('text-indent', '0px');
		} else {
			$('.claim-form p.red').css('text-indent', '-1000px');
		}
	});
	
	$('.btn-offers, .btn-savings').click(function() {
		$(this).addClass('pressed2');
		return false;
	});
	
	$('span[class*="indicator"]').mouseover(function() {
		var top = $(this).offset().top - 46;
		var left = $(this).offset().left - 11;
		if($('body').attr('id') == 'dashboard') {
			left = left + 4;
		}
		var color = $(this).attr('class').toString().split('-');
		var txt = $(this).attr('title');
		$(this).attr('title', '');
		var tooltip = '<div class="' + color[0] + '-tooltip" style="top: ' + top + 'px; left: ' + left + 'px;"><p>' + txt + '</p><div class="tooltip-r"></div></div>';
		$('body').append(tooltip);
	}).mouseout(function() {
		$(this).attr('title', $('body > div[class*="tooltip"]:visible').find('p').html());
		$('div[class*="tooltip"]').remove();
	});
	
	$('.new-offer').hover(function() {
		if($(this).hasClass('removed') == false) {
			$(this).find('.offer-info, .offer-overlay').toggle();
		}
	});
	
	$('.gift-box').click(function() {
		document.location = 'gift-offer.html';
		return false;
	});
	
	$('.my-points').click(function() {
		var hr = $(this).find('a').attr('href');
		document.location = hr;
	});
	
	$('.other-offers .shop-button').hover(function() {
		if($(this).parent().find('.save-button').is(':visible')) {
			$(this).parent().find('.save-button').show();
		}
		$(this).parent().find('.save-button').slideDown();
	}, function() {
		sav_btn = window.setTimeout(function() {
			$('.other-offers .save-button:visible').slideUp();
		}, 100);
	});
	
	$('.other-offers .save-button').hover(function() {
		$(this).show();
		window.clearTimeout(sav_btn);
	}, function() {
		$(this).slideUp();
	});
	
	$('.my-offers li, .other-offers li').live('mouseover', function() {
		if($(this).find('.added-tooltip').is(':visible') == false) {
			$(this).css('z-index', 15).addClass('offer-hover').siblings('.offer-hover').removeClass('offer-hover').parent().find('.shop-tooltip:visible').hide();
		
			$(this).find('.shop-tooltip').delay(1200).slideDown(0);
		}
	}).live('mousemove', function(e) {
		if($(e.target).hasClass('activate-button') || $(e.target).parents('.activate-button').length) {
			$(this).find('.shop-tooltip').stop().hide();
		}
		if($(e.target).hasClass('save-button') || $(e.target).parents('.save-button').length) {
			$(this).find('.shop-tooltip').stop().hide();
		}
		if($(e.target).hasClass('shop-button') || $(e.target).parents('.shop-button').length) {
			$(this).find('.shop-tooltip').stop().hide();
		}
	}).live('mouseout', function() {
		if($(this).find('.added-tooltip').is(':visible')) {
			$(this).css('z-index', 15);
		} else {
			if($(this).find('.shop-tooltip').is(':visible')) {
				$(this).css('z-index', 1).removeClass('offer-hover').find('.shop-tooltip').slideUp(0);
			} else {
				$(this).css('z-index', 1).removeClass('offer-hover').find('.shop-tooltip').stop().hide();
			}
		}
	});
	$('.new-offers .shop-button, .new-offers .activate-button, .new-offers .save-button').hover(function() {
		$(this).parents('li:eq(0)').find('.shop-tooltip').stop().hide();
	});
	
	$('.l-more').live('click', function() {
		$('.shop-tooltip:visible').hide().parents('li:eq(0)').removeClass('offer-hover').css('z-index', 5);
		$(this).parents('li:eq(0)').addClass('offer-hover').css('z-index', 15).find('.shop-tooltip').show();
		$(this).parents('li:eq(0)').siblings().css('z-index', 5);
		return false;
	});
	
	$('.my-offers li .added-tooltip').mouseover(function() {
		$(this).parents('li:eq(0)').find('.shop-tooltip').stop().hide();
		return false;
	}).mouseleave(function() {
		$(this).hide();
	});
	
	$('.share-offer').mouseover(function() {
		$(this).parents('.section-entry:eq(0)').parent().css('z-index', 10).siblings().css('z-index', 1);
	});
	
	$('.shop-tooltip').live('mouseover', function() {
		$(this).stop().show();
	}).live('mouseout', function() {
		$(this).stop().hide();
	});
	
	$('.offer-hover .shop-button').live('mouseover', function() {
		if($(this).parents('li:eq(0)').find('.shop-tooltip:visible').length) {
			$(this).parents('li:eq(0)').find('.shop-tooltip:visible').hide();
		}
	});
	
	$('.dismiss').click(function() {
		$(this).parents('li:eq(0)').animate({
			height: 70
		});
		$(this).parents('.new-offer:eq(0)').animate({
			opacity: 0,
			height: 0
		}, 500, function() {
			$(this).after('<p class="notification-box-grey" style="display: none;">This offer has been removed</p>');
			if($(this).parents('.new-offers').find('.section-entry > ul > li').length == 1) {
				$(this).parents('li:eq(0)').find('.notification-box-grey').slideDown(function() {
				$(this).parents('.new-offers').delay(2000).slideUp(function() {
					$(this).remove();
				});
			});
			} else {
				$(this).parents('li:eq(0)').find('.notification-box-grey').slideDown(function() {
				$(this).parents('li:eq(0)').delay(2000).slideUp(function() {
					$(this).remove();
				});
			});
			}
		});
		return false;
	});
	
	$('.test-container').click(function() {
		document.location = '../about-us.html#press';
		return false;
	});
	
	$('.offer-tab .save-button, .activate-button, .shop-button').click(function() {
		var hr = $(this).attr('href');
		var pts = $(this).attr('rel');
		
		if($(this).hasClass('save-button') || $(this).hasClass('shop-button')) {
			var notif_txt = 'Your offer has been saved in "My Offers"';
		}
		if($(this).hasClass('activate-button')) {
			var notif_txt = 'Your offer has been activated and moved to "My Offers"';
		}
		
		if($(this).parents('.new-offers').length) {
			$(this).parents('li:eq(0)').css('overflow', 'hidden').animate({
				height: 70
			});
			$(this).parents('li:eq(0)').find('.new-offer > *').slideUp(300);
			$(this).parents('.new-offer:eq(0)').addClass('removed').animate({
				opacity: 0,
				height: 0
			}, 500, function() {
				$(this).after('<p class="notification-box" style="display: none;">' + notif_txt + '</p>');
				if($(this).parents('.new-offers').find('.section-entry > ul > li').length == 1) {
					$(this).parents('li:eq(0)').find('.notification-box').slideDown(function() {
					$(this).parents('.new-offers').delay(2000).slideUp(function() {
						$(this).remove();
					});
				});
				} else {
					$(this).parents('li:eq(0)').find('.notification-box').slideDown(function() {
					$(this).parents('li:eq(0)').delay(2000).slideUp(function() {
						$(this).remove();
					});
				});
				}
			});
			
		} else {
			$(this).parents('li:eq(0)').animate({
				opacity: 0,
				width: 0
			}, 500, function() {
				if($(this).parents('.other-offers').find('.section-entry > ul > li').length == 1) {
					$(this).parents('.other-offers').slideUp(function() {
						$(this).remove();
					});
				} else {
					$(this).remove();
				}
			});
		}
		
		var old_pts = parseFloat($('.p-counter').text());
		var add_pts = parseInt(pts);
		var new_pts = (old_pts + add_pts).toString();
		var count_leng = $('.p-counter span').length;
		
		for(i=0;i<count_leng;i++) {
			if(new_pts.toString().length + i < count_leng) {
				$('.p-counter span').eq(i).html(0);
			} else {
				$('.p-counter span').eq(i).html(new_pts[i-1]);
			}
		}
		
		$.ajax({
			url: hr,
			type: 'GET',
			success: function(data) {
				$(data).css({
					width: 0,
					'overflow': 'hidden'
				}).prependTo('.my-offers ul').animate({
					width: 660
				}, 300, function() {
					$(this).css('overflow', 'visible');
					//var loadedTweetButton = new twttr.TweetButton($(this).find('a.twitter-share-button').get(0));
					//loadedTweetButton.render();
				});
			}
		});
		
		return false;
	});
	
	$('.new-offers .activate-button').hover(function() {
		var tt_offset = $(this).offset();
		$('.activate-tooltip').css({
			left: tt_offset.left + 144,
			top: tt_offset.top - 52
		}).show();
	}, function() {
		$('.activate-tooltip').hide();
	});
	
	$('#colorbox .share-buttons a').live('hover', function() {
		var tt_offset = $(this).position();
		var txt = $(this).attr('rel');
		$('.share-points span').text(txt).parent().parent().css({
			left: tt_offset.left + 42
		}).toggle();
	});
	
	initTimer('.timer span');
	
	if($('.tab-links').length) {
		$('.tab-links a:eq(0), .tab-entry:eq(0)').addClass('current');
	}
	
	$('.tab-links a').click(function() {
		if($(this).hasClass('current') == false) {
			$($(this).attr('href')).addClass('current').siblings('.current').removeClass('current');
			$(this).addClass('current').siblings('.current').removeClass('current');
		}
		return false;
	});
	
	$('#login-link').click(function() {
		$('.login-tooltip').show();
		return false;
	});
	
	$('body').click(function(e) {
		if($(e.target).parents('.login-tooltip').length == 0) {
			$('.login-tooltip').hide();
		}
	});
	
	$('.learn').click(function() {
		var scr_t = $($(this).attr('href')).offset().top;
		$('html, body').animate({
			scrollTop: scr_t
		});
		return false;
	});
	
	$('.vidlink').colorbox({iframe:true, innerWidth:425, innerHeight:344});
	
//	test_fade = window.setTimeout(function() {
//		initFader();
//	}, 4000);
	
//	$('.test-container .entries > div').each(function() {
//		if($(this).index() > 0) {
//			$(this).hide();
//		}
//	});
	
	$('.test-container .dots a').click(function() {
                eid = $(this).attr("data-eid");
                $("#tc").attr('data-cidx', eid);
                rotateTestimonials();
                
//		if($('.test-container div:visible').is(':animated') == false) {
//			window.clearTimeout(test_fade);
//			if($(this).hasClass('current') == false) {
//				var idx = $(this).index();
//				$('.test-container .entries > div:visible').removeClass('current').fadeOut(500);
//				$('.test-container .entries > div').eq(idx).fadeIn(500).addClass('current');
//				$(this).addClass('current').siblings('.current').removeClass('current');
//			}
//			test_fade = window.setTimeout(function() {
//				initFader();
//			}, 4000);
//		}
		return false;
	});
	
	$('#welcome .signup-box .box-head3 .checkbox').change(function() {
		if($(this).is(':checked')) {
//			$(".checkbox").removeAttr("disabled");
//			$(this).attr("disabled","true");
			
			$(this).parent().addClass('checked').siblings('.checked').removeClass('checked').find('.checkbox').attr('checked', false);
		} else {
			//$(this).parent().removeClass('checked');
			//alert("HERE ");
			$(this).parent().addClass('checked');
			$(this).attr("checked","checked");
		}
	});
	
	$('.history-table .arrow').click(function() {
		$(this).parents('.trow:eq(0)').find('.row-body').slideToggle()
		$(this).toggleClass('expanded');
		return false;
	});
	
	if($('.input-container').length) {
		$('.input-container .blink').val('');
	}
	
	$('#welcome-box .btn-continue').live('click', function() {
		$.colorbox.close();
		return false;
	});
	
	$('a.go-top').click(function() {
		$('html, body').animate({
			'scrollTop': 0
		},300);
		return false;
	});
	
	//about us functionality
	
	$(".about-us-link").click(function(){
		var that = this.id;
		var thatLink = that.split("-");
		if(thatLink[1] != "blog"){
			$(".aboutus-section").hide();
			$("#about-" + thatLink[1]).fadeIn(500);
			$(".about-us-link").removeClass("active-tab");
			$("#" + that).addClass("active-tab");
		}
	});
	
	//linkback helper
	if(!window.location.hash) {
		$("#about-ourstory").show();
	}
	$("#link-ourstory").addClass("active-tab");
	if(window.location.hash) {
		$("#about-team").hide();
  		var linkback = window.location.hash.split("#");
  		$("#about-" + linkback[1]).show();
		$(".about-us-link").removeClass("active-tab");
		$("#link-" + linkback[1]).addClass("active-tab");
  	}
	
	if ($.browser.msie && $.browser.version.substr(0,1)<7) {
		DD_belatedPNG.fix('#logo a, #welcome .signup-box, #welcome .signup-box .box-head3 .checklabel .ch-img, #welcome .signup-box .box-form .field-container, #buckets .buckets-center');
	};
	
});

$(window).load(function() {
	if($.browser.msie) {
		$('.fb_iframe_widget iframe').each(function() {
			$(this).css({
				width: 55,
				height: 22,
				'overflow': 'hidden'
			});
		})
	}
        rotateTestimonials();
        window.setInterval(function(){rotateTestimonials();}, 5000);
});

$(document).ajaxComplete(function(){
    /*try{
        FB.XFBML.parse(); 
    }catch(ex){}*/
});



$(document).ready(function(){
	//var home_timer_int = 0;
	// refreshValues();
//	alert("bam");
	/*function initHomeTimer() {
		
        refreshValues();
        $.ajax({
                url: "/l/index.php?module=Offers&action=getHomePageOfferCount",
                type: 'GET',
                success: function(data) {
                        //alert("HP: data: " + data);
                        d = $.parseJSON(data);
                        if ("Failure" == d['state']) {
                                alert('Failure: ' + d['count']);
                        } else if ("Success" == d['state']) {
                            new_timer_val = d['count'].toString();
                            $('.home-counter .nums span').each(function() {
                                    var idx = $(this).index();
                                    idx > 2 ? idx = idx-1 : idx = idx;
                                    $(this).text(new_timer_val[idx]);
                            });
                            refreshValues();
                           
                        }
                }
        });
	//
	//
	//
	//
	//refreshValues();
	//	
	//	home_timer = window.setInterval(function() {
	//                    
	//		var old_timer_val = parseFloat($('.home-counter .nums').text());
	//		                
	//		if(home_timer_int == 0) {
	//			var new_timer_val = (old_timer_val + 1).toString();
	//			
	//			home_timer_int++;
	//		} else {
	//			var new_timer_val = (old_timer_val + 2).toString();
	//			
	//			home_timer_int = 0;
	//		}
	//		
	//		$('.home-counter .nums span').each(function() {
	//			var idx = $(this).index();
	//			idx > 2 ? idx = idx-1 : idx = idx;
	//			$(this).text(new_timer_val[idx]);
	//		});
	//		
	//		refreshValues();
	//		
	//	}, 60000);
	};*/
	
	!function refreshValues() {
		$('.home-counter .nums span').each(function() {
			var bg_pos = '-' + parseInt($(this).text()) * 19 + 'px 0px';
			$(this).css('background-position', bg_pos);
		});
	}();
});


function rotateTestimonials() {
        startIdx = $("#tc").attr('data-cidx');
        startIdx = parseInt(startIdx);
        //alert(startIdx);

        for (j = 0; j < 8; j++) {
            if (startIdx != j) {
                $('#'+j).hide();
                $('#a'+j).removeClass('current');
            }
        }

        $('#'+startIdx).show();
        $('#a'+startIdx).addClass('current');
        //$('#'+startIdx).fadeOut(5000);
        if (startIdx == 7) {
            startIdx = 0;
        } else {
            startIdx += 1;
        }
        $("#tc").attr('data-cidx', startIdx);
                
}



function initTimer(container) {
	var time = parseInt($(container).text()) * 1000;
	
	connect_timer = window.setInterval(function() {
		time = time - 1000;
		if(time == 0) {
			window.clearInterval(connect_timer);
			$(container).text('0');
			formError();
		} else {
			$(container).text(time/1000);
		}
	}, 1000);
}

//function initFader() {
//	window.clearTimeout(test_fade);
//	var current = $('.test-container .entries > .current');
//	var next = current.next().length ? current.next() : current.parent().children(':first');
//	current.fadeOut(500, function() {
//		$(this).removeClass('current');
//	});
//	next.fadeIn(500).addClass('current');
//	$('.test-container .dots a').eq(next.index()).addClass('current').siblings('.current').removeClass('current');
//	img_fade = window.setTimeout(function() {
//		initFader();
//	}, 4000);
//}

function evenHeight() {
	var h = 0;
	
	$('.three-cols .box-entry').each(function() {
		if($(this).innerHeight() > h){
			h = $(this).innerHeight();
		}
	});
	$('.three-cols .box-entry').css('height', h - 70);
}

function formSuccess() {
	window.clearInterval(connect_timer);
	$('.form-head h3, .form-fields').slideUp();
	$('.connecting').slideDown(function() {
		$(this).parents('form').find('.form-body, .form-foot, .connecting').delay(1000).slideUp(function() {
			$('.success').slideDown();
			$('.congratulations').delay(1000).slideDown();
		});
	});
}

function formError() {
	$('.form-head h3, .form-fields').slideUp();
	$('.connecting').slideDown(function() {
		$(this).parents('form').find('.form-body, .form-foot, .connecting').delay(1000).slideUp(function() {
			$('.error').slideDown();
		});
	});
}
function autoSuggest(res) {
	var target_phrases = ["test phrase", "Wells fargo"];
	var query = res.toLowerCase();
	var match = null;
	for (var i=0; i < target_phrases.length; i++) {
		if (target_phrases[i].toLowerCase().indexOf(query)!==-1) {
			match = target_phrases[i];
			break;
		}
	}
	
	if (!match) {
		render_ac_result('no-result');
	} else if(query=='') {
		render_ac_result('empty');
	} else {
		render_ac_result('results.html');
	}
}

function render_ac_result(result) {
	var loader = '<div class="loader"><p>Loading</p></div>';
	var no_result = '<div class="no-results"><p>Sorry, no results found.</p></div>';
	
	if (result =='empty') {
		$('#card-search .autosuggest').hide();
		$('#card-search .field-container').find('.clear').hide();
	} else if (result == 'no-result') {
		$('#card-search .field-container .autosuggest').show(0, function() {
			$(this).parents('.field-container').find('.clear').show();
			var $th = $(this).html(loader);
			setTimeout(function () {
				$th.html(no_result);
			}, 500);
		});
	} else {
		$('#card-search .field-container .autosuggest').show(0, function() {
			$(this).parents('.field-container').find('.clear').show();
			var $th = $(this).html(loader);
			setTimeout(function () {
				$th.load(result);
			}, 500);
		});
	}
}

function log_utm_source(calling_page){
    	// This is logging code. No point in letting a rogue failure here affect anything else....hence the try...catch
     	try{
            	var queryStr = window.location.search;
              	var utm_source = "";
		if (queryStr != ""){
                    	queryStr = queryStr.split("?")[1];
                     	myparams = queryStr.split("&");
                     	for (param in myparams)
                     	{       
                           	temp = myparams[param].split("=");
                             	if(temp[0] == 'utm_source'){
                           		utm_source = temp[1];
				}
                   	}
         	}
		log_event(calling_page+ '-' + utm_source);
    	}catch(e){
                        //alert('effin exception');
    	}
}


function log_event(name) {
	$.post('/l/event.php?EVENT_NAME=' + name, function(){
		//alert("success");
	});
	return true;
}

function log_event2(name,url) {
	$.post('/l/event.php?EVENT_NAME=' + name, function(){
		window.location.href = url;
		//alert("success");
	});
}


