$(function(){

	var menuTimer,
		hideTimer,
		timeout = 50,
		easeIn = 250,
		easeOut = 150;

	$('#menu > ul > li').each(function(){

		var $thisMenu = $(this);
		var $hideMe = $thisMenu.parents('ul').find('ul').not(
			$thisMenu.find('ul')
		);

		$(this).mouseover(function(){

			clearTimeout(hideTimer)
			hideTimer = setTimeout(function(){
				$hideMe.fadeOut(easeOut);
			},timeout);

			clearTimeout(menuTimer);
			menuTimer = setTimeout(function(){
				$thisMenu.find('ul').eq(0).fadeIn(easeIn);
			},timeout);

		}).mouseout(function(){

			clearTimeout(menuTimer);
			menuTimer = setTimeout(function(){
				$thisMenu.find('ul').eq(0).fadeOut(easeOut);
			},timeout);

		}).find('ul').eq(0).hide();

	});
	
	$("input[type='text']").each(function(){
		$(this).checkPlaceholder();
	});
	
	var switchContactType = function ($form) {

		$form.find('.contacttypeEmail').hide();

		$form.find('input.contacttype').click(function() {

			if($(this).val() == '0') {
				$form.find('.contacttypeEmail').show();
				$form.find('.contacttypePhone').hide();
			} else {
				$form.find('.contacttypeEmail').hide();
				$form.find('.contacttypePhone').show();
			}

		});
	};
	
	var $quickQuote = $("#quickQuote");
	if($quickQuote.exists()) {
		switchContactType($quickQuote);
		$quickQuote.validate({
			rules: {
				phone: {
					number: true,
					required: true
				}
			}
		});
		
	}
	
	var $negotiateDealLink = $('.negotiateDealLink'),
		$offerDetailRequestQuoteLink = $('#requestQuoteLink'),
		$requestQuoteLinks = $('a[href="#requestaquote"]'),
		externalRequestQuote = (location.search).split("requestquote"),
		openQuickQuote = function(e) {
			
			e.preventDefault();
			
			$.get(
				'/offers/',
				{Ajax: 1,SearchKeyword: 'requestquote'},
				function(responsePage) {
					
					Shadowbox.open({
						player: 'html',
						content: responsePage,
						height: 760,
						title: 'Negotiate a deal',
						options: {
							onFinish: function() {
								
								var $ajaxForm = $("#ajax-container #quickQuote"),
									actionURL = $ajaxForm.attr('action');
								switchContactType($ajaxForm);
															
								$ajaxForm.validate({
									submitHandler: function(form) {
										//form.submit();
										$.post(
											actionURL,
											$ajaxForm.serialize(),
											function(responsePage) {
												
												
												/*response = "<h3>Thank you!</h3>";
												response = response + "<p>Your quote request has been submitted. We will respond as soon as possible.</p>"
												response = response + '<p>Alternatively you can <a class="chat-online" href="javascript:void(0)" onclick="wsa_open_chat(\'0\',\'0\')">chat with us online now.</a></p>'
												$("#ajax-container").html(response);*/
												$("#ajax-container").html(responsePage);
												$('.info-sent a').click(function() {
													Shadowbox.close();
												})
												
											} 
										);
										
										
										return false;
									}
								})
								
							}
						}
					});
					
				}
			);

			
			return false;
			
		};
		
	$offerDetailRequestQuoteLink.attr("rel", "").click(function(event) {
		openQuickQuote(event);
	});
			
	$negotiateDealLink.click(function(event) {
		openQuickQuote(event);
	});
	
	$requestQuoteLinks.click(function(event) {
		openQuickQuote(event);
	});
	
	if(externalRequestQuote.length > 1) {
		$(window).load(function() {
			openQuickQuote(event);
		})
	}	
	
	
	var $cctabs = $("#cc-tabs");
		
	$cctabs.alttabs();
	
	if($cctabs.exists()) {
		
		var $couponLink = $cctabs.find('#cctabs-learn-coupons'),
			$cashbackLink = $cctabs.find('#cctabs-learn-cashback');
			
		$couponLink.bind('click',function(event) {
			
			event.preventDefault();
			var $this = $(this);
			
			$.get(
				$this.attr("href"),
				{Ajax: 1},
				function(responsePage) {
					
					Shadowbox.open({
						player: 'html',
						content: responsePage,
						height: 500,
						title: $this.attr('title')
					});
					
				}
			);
			
		});
		
		$cashbackLink.bind('click',function(event) {
			
			event.preventDefault();
			var $this = $(this);
			
			$.get(
				$this.attr("href"),
				{Ajax: 1},
				function(responsePage) {
					
					Shadowbox.open({
						player: 'html',
						content: responsePage,
						height: 500,
						title: $this.attr('title')
					});
					
				}
			);
			
		});
		
	}
	


	var $searchResults = $("#searchresults li");
	if($searchResults.exists()) {
		
		for(var i=0; i < $searchResults.length; i++) {
			balance_height("#searchresults li:eq("+i+")", "#searchresults li:eq("+(++i)+")", 
							"#searchresults li:eq("+(++i)+")");
		}
		
		$searchResults.each(function() {
			var $this = $(this),
				link = $this.find('.offer-link').attr('href');
				
			$this.click(function() {
				window.location.href = link;
			})
		});				
	}
	
	if($("#image-rotator").exists()) {
		$("#image-rotator").cycle({
				timeout: 6500,
				fx:     'fade',
				next:  '#carousel-next',
				prev:  '#carousel-prev'
			});		
	}
	
	var $claimAcc = $('#claimLinks'),
		$newClaimLink = $('#new-claim'),
		$newClaimDiv = $('#cta-newclaim'),
		$existingClaimLink = $('#existing-claim'),
		$existingClaimDiv = $('#cta-existingclaim');
		
	if($claimAcc.exists()) {
		
		$newClaimLink.click(function() {
			if($existingClaimDiv.is(':visible')) {
				$existingClaimDiv.slideUp(200);
			}
			if($newClaimDiv.is(':hidden')) {
				$newClaimDiv.slideDown(200);
			} else {
				$newClaimDiv.slideUp(200);
			}
			
			return false;
			
		});
		
		$existingClaimLink.click(function() {
			if($newClaimDiv.is(':visible')) {
				$newClaimDiv.slideUp(200);
			}
			if($existingClaimDiv.is(':hidden')) {
				$existingClaimDiv.slideDown(200);
			} else {
				$existingClaimDiv.slideUp(200);
			}
			
			return false;
			
		});
		
	}
		
	// offer-details page
	
	if($("#deal-carousel").exists()) {
		$("#deal-carousel").cycle({
				fx:     'fade',
				next:  '#carousel-next',
				prev:  '#carousel-prev'
			});		
	}
	
	var $tabs = $("#offer-tabs");
	if($tabs.exists() && !$tabs.hasClass('fullwidth')) {		
		$("#offer-tabs").alttabs();
	}
	
	$("#large-links a.where-to-buy").click(function() {
		
		$tabs.find('.nav li:eq(2)').click();
		
		return false;
		
	});
	
	// form.cfm
	var $claims_form = $("#claims-form"),
		$packages = $(".col2 .packageWP", $claims_form);
	if($packages.exists()) {
		var $radiobtns = $("input[type='radio']", $packages);
		
		if(!$packages.hasClass('selected')) {
			$packages.eq(0).addClass('selected').find("input[type='radio']").attr('checked', true);
		}
		
		$radiobtns.click(function(){
			$packages.removeClass('selected');
			$(this).closest('.packageWP').addClass('selected');
		});
	}
	
	$(".feedbackStars").stars();
	
	$('input.uploadUI').each(function() {
		$(this).uploadUI();
	});
	
	
	//selectrecipt.cfm
	$("#haventBought").click(function(e) {
		e.preventDefault();
		
		$.get(
			$(this).attr('href'),
			{Ajax: 1},
			function(responsePage) {
				
				Shadowbox.open({
					player: 'html',
					content: responsePage,
					height: 500,
					title: 'Haven&#39;t bought yet',
					options:{onClose: function() {
								$("div.blockPage").hide();
							}}
				});
				
			}
		);
		
		return false;
		
	});
	
	//claims page
	$(".clipcodeWP").each(function() {

    	var $thisCopy = $(this);

        //Create a new clipboard client
        var clip = new ZeroClipboard.Client();

        //Glue the clipboard client to the last td in each row
        clip.glue($thisCopy[0]);

        //Grab the text from the parent row of the icon
        var $input = $thisCopy.find('input.clipcode');
        if($input.length > 0) {
	        var txt = $input.val();        	
        } else {
        	
        	var txt = $thisCopy.first().contents().filter(function() {
					    return this.nodeType == 3;
					}).text();
        	
        }
        clip.setText(txt);

        //Add a complete event to let the user know the text was copied
        clip.addEventListener('complete', function(client, text) {
			window.open($thisCopy.attr('rel'));
        });
        clip.addEventListener('mouseover', function(client, text) {
			$thisCopy.find('.cliptip').fadeIn(200);
        });
        clip.addEventListener('mouseout', function(client, text) {
			$thisCopy.find('.cliptip').fadeOut(200);
        });

    });
    
    //tooltip
    $('.tooltip').hover(function() {
    	$('.tooltipDivs', this).stop(true,true).fadeIn(200);
    }, function() {
    	$('.tooltipDivs', this).stop(true,true).fadeOut(200);
    });
    
    $('#receipt-upload').submit(function() {
    	if($('input[type="file"]', this).val() === '') {
    		alert('Please select a file before submitting.');
    		return false;
    	} 
    	return true;
    });
    $('.claiminfo form').submit(function() {
    	if($('input[type="file"]', this).val() === '') {
    		alert('Please select a file before submitting.');
    		return false;
    	} 
    	return true;
    });
    
    $("#OfferFeedbackForm").submit(function() {
    	$('input[type="hidden"]', this).removeAttr('disabled');
    });
    
    
    //autocomplete
    
   

});

var _CF_checkquickQuote  = function(){};

$(window).load(function(){
	
})



/* 
 * @author: sgowda
 * @desc: 	Had to write this plugin for tabs as jquery ui tabs didn't work for some strange reason
 * 			also this was helpful as I had control over classes for next and prev
 */
jQuery.fn.alttabs = function(){
	/* TODO: @sgowda > Add lots of options like speed, tansition, callback & etc. */
	if(this.length == 0) return false;
	var $offer_tabs = $(this),
		$offer_tabs_nav = $("ul.nav li", $offer_tabs),
		$offer_tabs_divs = $offer_tabs.children("div").hide(),
		$curr_nav = $offer_tabs_nav.eq(0).addClass("active"),
		$curr_div = $($curr_nav.find('a').attr('href'), $offer_tabs).show();

	$curr_nav.next().addClass("next");
	$curr_nav.prev().addClass("prev");

	var	switchTab = function(){
		$curr_nav.removeClass("active");
		$curr_nav.next().removeClass("next");
		$curr_nav.prev().removeClass("prev");
		$curr_div.hide();
		$curr_nav = $(this).addClass("active");
		$curr_div = $($curr_nav.find('a').attr('href'), $offer_tabs).show();
		$curr_nav.next().addClass("next");
		$curr_nav.prev().addClass("prev");
		return false;
	};
		
	$offer_tabs_nav.bind("click", switchTab);
}

//function to check if an element exists
jQuery.fn.exists = function(){return jQuery(this).length>0;}

// function to check placeholder text for inputs
jQuery.fn.checkPlaceholder = function() {
	var $this = $(this),
		placeHolderText = $this.attr("title");
		// console.debug("$this",$this);
		// console.debug("placeHolderText",placeHolderText);
	if(placeHolderText !== undefined) {
		$this.blur(function(){
			if($this.val() == "") {
				$this.val(placeHolderText);
			}
		});
		$this.focus(function(){
			if($this.val() === placeHolderText) {
				$this.val("");
			}
		});
	}
}

/* 
 * @author: sgowda
 * @desc: Plugin for styling file inputs.(more description needed)
 * TODO: Add options.
 */
jQuery.fn.uploadUI = function() {
	var $this = $(this);

	if($this.is(':input[type="file"]')) {
		
		var $input = $('<span class="uploadUI-input"></span>'),
			$button = $('<span class="uploadUI-button"></span>'),
			//thisOffset = $this.offset(),
			$wrapperDiv = $('<span class="uploadUI-div"></span>');
		
		$this.wrap($wrapperDiv);
		$input.insertAfter($this);
		$button.appendTo($input);
		$this.css("opacity", "0");
		
		//$input.css("top", thisOffset.top);
		$this.change(function() {
			var fileName = $this.val();
			fileName = fileName.split('\\');
			//var ext = fileName[fileName.length -1].split('.');
			fileName = fileName[fileName.length -1];
			if(fileName.length > 15) {
				fileName = fileName.substring(0, 15);
				fileName = fileName + '...'
				/*if(ext.length > 1) {
					fileName = fileName + ext[ext.length-1];
				}	*/			
			}
			 
			$input.text(fileName);
		});
		
		$input.bind("focus", function(event) { 
			console.log(event.type)
			$this.click();
		});
		
	} else {
		return false;
	}
}

//function to balance divs' height
function balance_height() {
	var max_height = 0;
	if(arguments.length > 1) {
		for(var i = 0; i < arguments.length; i++) {
			if(jQuery(arguments[i]).outerHeight(true) > max_height)
				max_height = jQuery(arguments[i]).outerHeight(true);
		}
		var paddingtop, paddingbottom, borderTop, borderBottom;
		for(var i = 0; i < arguments.length; i++) {
			//if($(arguments[i]).outerHeight(true) < max_height) {
				temp = max_height;
				var paddingtop = 0,paddingbottom = 0,borderTop = 0,borderBottom = 0,margintop = 0,marginbottom = 0;
				if($(arguments[i]).css("padding-top") != undefined) {
					paddingtop = parseInt($(arguments[i]).css("padding-top").replace("px", ""));
					if(paddingtop > 0) temp = temp - paddingtop;
				}
				if($(arguments[i]).css("padding-bottom") != undefined) {
					paddingbottom = parseInt($(arguments[i]).css("padding-bottom").replace("px", ""));
					if(paddingbottom > 0) temp = temp - paddingbottom;
				}
				if($(arguments[i]).css("border-top-width") != undefined) {
					borderTop = parseInt($(arguments[i]).css("border-top-width").replace("px", ""));
					if(borderTop > 0) temp = temp - borderTop;
				}
				if($(arguments[i]).css("border-bottom-width") != undefined) {
					borderBottom = parseInt($(arguments[i]).css("border-bottom-width").replace("px", ""));
					if(borderBottom > 0) temp = temp - borderBottom;
				}
				if($(arguments[i]).css("margin-top") != undefined) {
					margintop = parseInt($(arguments[i]).css("margin-top").replace("px", ""));
					if(margintop > 0) temp = temp - margintop;
				}
				if($(arguments[i]).css("margin-bottom") != undefined) {
					marginbottom = parseInt($(arguments[i]).css("margin-bottom").replace("px", ""));
					if(marginbottom > 0) temp = temp - marginbottom;
				}
				$(arguments[i]).height(temp);
				//alert(temp+","+max_height+","+paddingtop+","+paddingbottom+","+borderTop+","+borderBottom+","+margintop+","+marginbottom);
			//}
		}
	}
}

