VISA.include_js("/js/jquery/jquery.bgiframe.min.js");

var allMerchantsTimeoutHide;
var allMerchantsTimeoutShow;
var allMerchantsReady = false;

// Stop IE from always trying to download background images
try
{
    document.execCommand("BackgroundImageCache", false, true);
}
catch(exception)
{
    // Do nothing
}

$(document).ready(function() {

    checkAllMerchants();

	//////////////////////////////////
	// ALL MERCHANTS TOOLTIP BEGINS //
	//////////////////////////////////

	$(".all_merchants").hover(function() {
		if(allMerchantsReady) {
			$(this).css("cursor", "pointer");
			$(this).addClass("hover");
	
			if(allMerchantsTimeoutHide) { window.clearTimeout(allMerchantsTimeoutHide); }
	
			allMerchantsTimeoutShow = setTimeout(function() {
	            $("#all_merchants_a-d").show();
	            $("#all_merchants_e-h").hide();
	            $("#all_merchants_i-r").hide();
	            $("#all_merchants_s-z").hide();
	            $("#all_merchants_a-d_link").addClass("alpha_cat_selected");
	            $("#all_merchants_e-h_link").removeClass("alpha_cat_selected");
	            $("#all_merchants_i-r_link").removeClass("alpha_cat_selected");
	            $("#all_merchants_s-z_link").removeClass("alpha_cat_selected");
	            
	            $(".all_merchants_tooltip").css({ "left": $('.all_merchants').offset().left + 150, "top": $('.all_merchants').offset().top + -38 }); 
	
	            $(".all_merchants_tooltip").show();
	        }, 400);
		}
    }, function() {
		if(allMerchantsReady) {
			$(this).css("cursor", "auto");
	
			allMerchantsTimeoutHide = setTimeout(function() { $(".all_merchants_tooltip").hide(); }, 1000);
	
			if(allMerchantsTimeoutShow) { window.clearTimeout(allMerchantsTimeoutShow); }
		}
	});

	$(".all_merchants_tooltip").hover(function() {
		$(".all_merchants_tooltip").show();

		if(allMerchantsTimeoutHide) { window.clearTimeout(allMerchantsTimeoutHide); }
    }, function() {
		allMerchantsTimeoutHide = setTimeout(function() { $(".all_merchants_tooltip").hide(); }, 1000);
	});

	$("#all_merchants_a-d_link, #all_merchants_e-h_link, #all_merchants_i-r_link, #all_merchants_s-z_link").hover(function() {
		$(this).css("cursor", "pointer");
		$(this).addClass("alpha_cat_hover");
    }, function() {
		$(this).css("cursor", "auto");
		$(this).removeClass("alpha_cat_hover");
	});

	$("#all_merchants_a-d_link").click(function() {
		$("#all_merchants_a-d").show();
		$("#all_merchants_e-h").hide();
		$("#all_merchants_i-r").hide();
		$("#all_merchants_s-z").hide();
		$("#all_merchants_a-d_link").addClass("alpha_cat_selected");
		$("#all_merchants_e-h_link").removeClass("alpha_cat_selected");
		$("#all_merchants_i-r_link").removeClass("alpha_cat_selected");
		$("#all_merchants_s-z_link").removeClass("alpha_cat_selected");
	});

	$("#all_merchants_e-h_link").click(function() {
		$("#all_merchants_a-d").hide();
		$("#all_merchants_e-h").show();
		$("#all_merchants_i-r").hide();
		$("#all_merchants_s-z").hide();
		$("#all_merchants_a-d_link").removeClass("alpha_cat_selected");
		$("#all_merchants_e-h_link").addClass("alpha_cat_selected");
		$("#all_merchants_i-r_link").removeClass("alpha_cat_selected");
		$("#all_merchants_s-z_link").removeClass("alpha_cat_selected");
	});

	$("#all_merchants_i-r_link").click(function() {
		$("#all_merchants_a-d").hide();
		$("#all_merchants_e-h").hide();
		$("#all_merchants_i-r").show();
		$("#all_merchants_s-z").hide();
		$("#all_merchants_a-d_link").removeClass("alpha_cat_selected");
		$("#all_merchants_e-h_link").removeClass("alpha_cat_selected");
		$("#all_merchants_i-r_link").addClass("alpha_cat_selected");
		$("#all_merchants_s-z_link").removeClass("alpha_cat_selected");
	});

	$("#all_merchants_s-z_link").click(function() {
		$("#all_merchants_a-d").hide();
		$("#all_merchants_e-h").hide();
		$("#all_merchants_i-r").hide();
		$("#all_merchants_s-z").show();
		$("#all_merchants_a-d_link").removeClass("alpha_cat_selected");
		$("#all_merchants_e-h_link").removeClass("alpha_cat_selected");
		$("#all_merchants_i-r_link").removeClass("alpha_cat_selected");
		$("#all_merchants_s-z_link").addClass("alpha_cat_selected");
	});

	////////////////////////////////
	// ALL MERCHANTS TOOLTIP ENDS //
	////////////////////////////////

	/////////////////////////////////
	// DETAIL OFFER TOOLTIP BEGINS //
	/////////////////////////////////

	$(".landing_offer").hover(function() {
		$(this).css("cursor", "pointer");
		$(this).addClass("hover");
    }, function() {
		$(this).css("cursor", "auto");
		$(this).removeClass("hover");
	});

	$(".landing_offer").click(function(event) {
		$("#detail_offer_tc").hide();
		displayDetailOfferTooltip(event, $(this));
		return false;
		
	});

	$(".category_offer").hover(function() {
		$(this).css("cursor", "pointer");
		$(this).addClass("hover");
    }, function() {
		$(this).css("cursor", "auto");
		$(this).removeClass("hover");
	});

	$(".category_offer").click(function(event) {
		$("#detail_offer_tc").hide();
		displayDetailOfferTooltip(event, $(this));
		return false;
	});

    // stop dropdowns showing through the detail offer tooltip on IE6
    $(".detail_offer_tooltip").bgiframe();

	///////////////////////////////
	// DETAIL OFFER TOOLTIP ENDS //
	///////////////////////////////
	
	///////////////////////////////
	// DETAIL PAGE SHARE OVERLAY //
	///////////////////////////////	
	
	$("#detail_btnShare_detail img").unbind("hover").hover(function() {
		$(this).attr("src", "/img/other/btn-share-over.gif");
		$(this).css("cursor", "pointer");
	}, function() {
		$(this).attr("src", "/img/other/btn-share.gif");
		$(this).css("cursor", "auto");
	});

	$("#detail_btnShare_detail img").unbind("click").click(function(e) {
		var panelOffset = $("#detail_btnShare_detail").offset();
		$(".detail_share_overlay_detail").css({ "left": panelOffset.left + 307, "top": panelOffset.top + 5, "width": "115px" });
		$(".detail_share_overlay_detail").show();
		e.preventDefault();
	});

	$(".detail_share_overlay_top").unbind("hover").hover(function() {
		$(this).css("cursor", "pointer");

	}, function() {
		$(this).css("cursor", "auto");

	});	

	$(".detail_share_overlay_top").unbind("click").click(function(e) {
		$(".detail_share_overlay_detail").hide();
		e.preventDefault();
	});

	////////////////////////////////////
	// DETAIL PAGE SHARE OVERLAY ENDS //
	////////////////////////////////////
	
	
	/////////////////////////////////////////
	// SIGNATURE DETAIL PAGE SHARE OVERLAY //
	/////////////////////////////////////////	
	
	$("#detail_btnShare_signature img").unbind("hover").hover(function() {
		$(this).attr("src", "/img/other/btn-share-over.gif");
		$(this).css("cursor", "pointer");
	}, function() {
		$(this).attr("src", "/img/other/btn-share.gif");
		$(this).css("cursor", "auto");
	});

	$("#detail_btnShare_signature img").unbind("click").click(function(e) {
		var sigOffset = $("#detail_btnShare_signature").position();
		console.log(sigOffset);
		$(".detail_share_overlay_signature").css({ "left": sigOffset.left + 427, "top": sigOffset.top + 145, "width": "115px" });
		$(".detail_share_overlay_signature").show();
		e.preventDefault();
	});
	
	$(".detail_share_sig_top").unbind("hover").hover(function() {
		$(this).css("cursor", "pointer");

	}, function() {
		$(this).css("cursor", "auto");

	});	

	$(".detail_share_sig_top").unbind("click").click(function(e) {
		$(".detail_share_overlay_signature").hide();
		e.preventDefault();
	});

	//////////////////////////////////////////////
	// SIGNATURE DETAIL PAGE SHARE OVERLAY ENDS //
	//////////////////////////////////////////////		
	
	$.preloadImages(
		"/img/other/bebo_ico.gif",
		"/img/other/email_ico.gif",
		"/img/other/facebook_ico.gif",
		"/img/other/myspace_ico.gif",
		"/img/other/twitter_ico.gif",
		"/img/other/callout_bg.jpg",
		"/img/other/share_overlay_top.gif",
		"/img/other/share_overlay_btm.gif",
		"/img/other/btn-share.gif",
		"/img/other/btn-share-over.gif"
	);	
});

function buildCategoryURL(categoryId, categoryName) {
    var url = "";

    if(categoryId && categoryName) {
        var tidiedCategoryName = categoryName.replace(/ /g, "").replace(/&/g, "");

        url += sectionPrefix + "/detail/";
        url += tidiedCategoryName;
        url += "/vro_details.jsp";
        url += "?pageId=" + pageId;
        url += "&categoryId=" + categoryId;
        url += "&categoryName=" + tidiedCategoryName;

        if(sectionSuffix) {
            url += sectionSuffix;
        }
    }

    return url;
}

function buildMerchantURL(merchantId, merchantName) {
    var url = "";

    if(merchantId && merchantName) {
        var tidiedMerchantName = merchantName.replace(/ /g, "").replace(/&/g, "");

        url += sectionPrefix + "/detail/";
        url += tidiedMerchantName;
        url += "/vro_details.jsp";
        url += "?pageId=" + pageId;
        url += "&merchantId=" + merchantId;
        url += "&merchantName=" + tidiedMerchantName;

        if(sectionSuffix) {
            url += sectionSuffix;
        }

        $("#detail_offer_more_link:hidden").show();
    }
    else {
        $("#detail_offer_more_link:visible").hide();
    }

    return url;
}

function buildRedeemURL(offerId, offerName, redeemURL) {
    var url = "";

    if(offerId && offerName) {
        var tidiedOfferName = offerName.replace(/ /g, "").replace(/&/g, "");

        url += VISA.base_href;
        url += sectionPrefix + "/detail/";
        url += tidiedOfferName;
        url += "/vro_redeem.jsp";
        url += "?offerId=" + offerId;
        url += "&url=" + redeemURL;

        if(sectionSuffix) {
            url += sectionSuffix;
        }
    }

    return url;
}

function displayDetailOfferTooltip(event, offer) {
    $("#detail_tooltip_text img:visible").hide();
    $(".detail_offer_tooltip:visible").hide();
    $("#detail_tooltip_text:visible").hide();
    /*
    // unbind any links event before empty the div
    $(".detail_share_overlay_bottom a").unbind("click");
    */
    $(".detail_share_overlay_bottom ul").html("");
    $(".detail_share_overlay").hide();
    $("#detail_btnShare").hide();
    $("#tooltip_progress:hidden").show();

    var offerURL = $("a", offer).attr("href");

    $.getJSON(offerURL + "&json=true", function(json) { populateDetailOfferTooltip(json, offerURL); });

    $("#detail_offer_logo img").unbind("load");
    $("#detail_offer_logo img").attr("src", "/img/spacer.gif");
    $("#detail_offer_logo img").load(function() {
		$(this).show();
	});
    $("#detail_offer_logo img").attr("src", offer.find("img").eq(0).attr("src"));

	//carousel detail overlay positioning for IE6
	if ( (offer.parent().hasClass('sig_carousel_offers') || offer.parent().parent().hasClass('sig_carousel_offers')) ) {
	//we're in a carousel
    
		if (jQuery.browser.msie) {
			//browser is IE
			if((window.XMLHttpRequest == undefined) && (ActiveXObject != undefined)) {
				//version is IE6
			    	varTop = 20;
  				varLeft = 20;
			}
			else {
    	    			varTop = 10;
  				varLeft = 10;			
			}
		}
		else {
    	    		varTop = 10;
  			varLeft = 10;		
		}
		
	}
	
	else {
    	    	varTop = 10;
  		varLeft = 10;	
	}
    
    $(".detail_offer_tooltip").css({ "left": offer.offset().left + varLeft, "top": offer.offset().top + varTop });

    // Always hide terms and conditions when opening an offer tooltip
    $("#detail_offer_tc:visible").hide();
    $("#detail_offer_tc_link").css("background-image", "none");

    $(".detail_offer_tooltip").show();
	
	// Set up the print link
	$("#detail_offer_printable").html("<a href='" + $("a", offer).attr("href") + "&printable=yes' target='_blank'><img border='0' alt='Printable Page' src='/img/other/printable_page.gif' style='display: inline; cursor: auto;'/></a>");
}

function populateDetailOfferTooltip(json, offerURL) {
    /*
    // tracking variable for destination on share
    var params = {};
    var removeTimer;
    if ((/\?/).test(offerURL)) {
        var dest = offerURL.split(/\?/);
        //params.destination = dest[0];
        params.dest_query = dest[1];
    }
    */
    $("#detail_offer_logo img").attr("alt", json.merchantName);
    $("#detail_offer_desc").html(json.shortDescriptionFull);
    $("#detail_offer_related_link a").attr("href", buildCategoryURL(json.categoryId, json.categoryName));
    $("#detail_offer_more_link a").attr("href", buildMerchantURL(json.merchantId, json.merchantName));
    $("#detail_offer_content").html("<p>"+json.longDescriptionFull);
    $("#detail_offer_valid_date").html("Valid from " + json.startDate + " to " + json.endDate);
    
    //display share button - needs to check for variables in json
    
    if(json.share == 'Y') {
    	$("#detail_btnShare").show();
    	$("#detail_btnShare img").show();
    }

    if(json.offerLogo2)
    {
        $("#detail_offer_second_logo img").attr("src", json.offerLogo2);
        $("#detail_offer_second_logo:hidden").show();
        $("#detail_offer_second_logo img:hidden").show();
    }
    else
    {
        $("#detail_offer_second_logo:visible").hide();
    }

    $("#detail_offer_tc ul").html(json.additionalTerm + json.visaterms);

    $("#detail_offer_redeem a").unbind("click");

    if(json.redeemUrl)
    {
        // Setup redeem URL including analytics
        $("#detail_offer_redeem a").attr("href", unescape(json.redeemUrl));
        $("#detail_offer_redeem a").click(function() {
            var request = $.ajax({ async: false, url: buildRedeemURL(json.id, json.name, json.redeemUrl) });
            var timeout = (new Date()).getTime() + 500;

            while (true) {
                if (request.readyState >= 2) break;
                if ((new Date()).getTime() >= timeout) break;
            }
        });

        $("#detail_offer_redeem:hidden").show();
    }
    else
    {
        $("#detail_offer_redeem:visible").hide();
    }

    $("#detail_offer_printable img:hidden, #detail_offer_closewindow img:hidden, #detail_offer_related_link img:hidden, #detail_offer_more_link img:hidden, #detail_offer_redeem img:hidden").show();
    $("#detail_offer_tc_link").css("background-image", "url('/img/other/sm_arrow_right.gif')");
    $("#tooltip_progress:visible").hide();
    $("#detail_tooltip_text:hidden").show();

	$("#detail_offer_printable img").unbind("hover").hover(function() {
		$(this).css("cursor", "pointer");
    }, function() {
		$(this).css("cursor", "auto");
	});

	/*$("#detail_offer_printable img").unbind("click").click(function() {
		$("body").addClass("print");
		print();
	});*/

	$("#detail_offer_closewindow img").unbind("hover").hover(function() {
		$(this).css("cursor", "pointer");
    }, function() {
		$(this).css("cursor", "auto");
	});
	

	$("#detail_offer_closewindow img").unbind("click").click(function() {
		$(".detail_offer_tooltip").hide();
		$(".dropBenefits").removeClass("hide");
		$("#card").removeClass("hide");
		$(".detail_share_overlay").hide();
	});

	$("#detail_offer_tc_link").unbind("click").click(function() {
        if($("#detail_offer_tc").is(":hidden")) {
            $("#detail_offer_tc").show();
            $(this).css({ "background-image": "url('/img/other/sm_arrow_down.gif')", "padding-bottom": "10px" });
        } else {
            $("#detail_offer_tc").hide();
            $(this).css({ "background-image": "url('/img/other/sm_arrow_right.gif')", "padding-bottom": "0" });
        }
	});

	$("#detail_offer_tc_link").unbind("hover").hover(function() {
		$(this).css({ "cursor": "pointer", "text-decoration": "underline" });
    }, function() {
		$(this).css({ "cursor": "auto", "text-decoration": "none" });
	});
	
	
	$("#detail_btnShare img").unbind("hover").hover(function() {
		$(this).attr("src", "/img/other/btn-share-over.gif");
		$(this).css("cursor", "pointer");
    	}, function() {
    		$(this).attr("src", "/img/other/btn-share.gif");
    		$(this).css("cursor", "auto");
	});
	
	$("#detail_btnShare img").unbind("click").click(function(e) {
		var panelOffset = $("#detail_btnShare").offset();
		$(".detail_share_overlay").css({ "left": panelOffset.left - 48, "top": panelOffset.top + 5, "width": "115px" });
		$(".detail_share_overlay").show();
        /*
        //force tracking to use offer URL param.  Remove after tracking is done otherwise it will be wrong on the whole page
        VISA.Analytics.addParameters(params);
        removeTimer = setTimeout(function(){VISA.Analytics.removeParameters(params)}, 200);
        */
		e.preventDefault();
	});
	
	
	if(json.email) {
		emailLink = "/vro/templates/email_form.jsp?id=" + json.id + "&email=" + json.email;
		$("<li><a id='share_email' href=\"javascript:pop_email(emailLink);\">Email</a></li>").appendTo(".detail_share_overlay_bottom ul");
	}
	
	if(json.facebook) {
		facebookLink = json.facebook;
		$("<li><a id='share_facebook' href=\"javascript:pop_facebook(facebookLink);\" class='facebook'>Facebook</a></li>").appendTo(".detail_share_overlay_bottom ul");
	}
	
	if (json.myspace) {
		myspaceLink = json.myspace;
		$("<li><a id='share_myspace' href=" + myspaceLink +  " class='myspace' target='_blank'>MySpace</a></li>").appendTo(".detail_share_overlay_bottom ul");
	}
	
	if (json.twitter) {
		twitterLink = json.twitter;
		$("<li><a id='share_twitter' href=" + twitterLink +  " class='twitter' target='_blank'>Twitter</a></li>").appendTo(".detail_share_overlay_bottom ul");
	}
	
	if(json.bebo) {
		beboLink = json.bebo;
		$("<li><a id='share_bebo' href=\"javascript:pop_bebo(beboLink);\" class='bebo'>Bebo</a></li>").appendTo(".detail_share_overlay_bottom ul");
	}	
	
	
	$(".detail_share_overlay_top").unbind("hover").hover(function() {
		$(this).css("cursor", "pointer");

    	}, function() {
    		$(this).css("cursor", "auto");
   		
	});	
	
	$(".detail_share_overlay_top").unbind("click").click(function(e) {
		$(".detail_share_overlay").hide();
		e.preventDefault();
	});

    /*
    // add click event listern to shars links so taht we can track analytics on offer id
    $('.detail_share_overlay_bottom a').bind("click", function(e){
        if(removeTimer) clearTimeout(removeTimer);
        VISA.Analytics.addParameters(params);
        removeTimer = setTimeout(function(){VISA.Analytics.removeParameters(params)}, 200);
    });
    */

}

function checkAllMerchants() {
	if(!allMerchantsReady) {
		if(typeof(merchantListAD) == "undefined") {
			window.setTimeout(checkAllMerchants, 1000);
		} else {
			allMerchantsReady = true;
			setupAllMerchants();
		}
	}
}

function setupAllMerchants() {
    for(var i = 0; i < Math.round(merchantListAD.length / 2); i++)
    {
        $("#all_merchants_a-d .all_merchants_left_col ul").append('<li><a href="' + buildMerchantURL(merchantListAD[i].id, merchantListAD[i].name) + '">' + merchantListAD[i].name + '</a></li>');
    }

    for(var i = Math.round(merchantListAD.length / 2); i < merchantListAD.length; i++)
    {
        $("#all_merchants_a-d .all_merchants_right_col ul").append('<li><a href="' + buildMerchantURL(merchantListAD[i].id, merchantListAD[i].name) + '">' + merchantListAD[i].name + '</a></li>');
    }

    for(var i = 0; i < Math.round(merchantListEH.length / 2); i++)
    {
        $("#all_merchants_e-h .all_merchants_left_col ul").append('<li><a href="' + buildMerchantURL(merchantListEH[i].id, merchantListEH[i].name) + '">' + merchantListEH[i].name + '</a></li>');
    }

    for(var i = Math.round(merchantListEH.length / 2); i < merchantListEH.length; i++)
    {
        $("#all_merchants_e-h .all_merchants_right_col ul").append('<li><a href="' + buildMerchantURL(merchantListEH[i].id, merchantListEH[i].name) + '">' + merchantListEH[i].name + '</a></li>');
    }

    for(var i = 0; i < Math.round(merchantListIR.length / 2); i++)
    {
        $("#all_merchants_i-r .all_merchants_left_col ul").append('<li><a href="' + buildMerchantURL(merchantListIR[i].id, merchantListIR[i].name) + '">' + merchantListIR[i].name + '</a></li>');
    }

    for(var i = Math.round(merchantListIR.length / 2); i < merchantListIR.length; i++)
    {
        $("#all_merchants_i-r .all_merchants_right_col ul").append('<li><a href="' + buildMerchantURL(merchantListIR[i].id, merchantListIR[i].name) + '">' + merchantListIR[i].name + '</a></li>');
    }

    for(var i = 0; i < Math.round(merchantListSZ.length / 2); i++)
    {
        $("#all_merchants_s-z .all_merchants_left_col ul").append('<li><a href="' + buildMerchantURL(merchantListSZ[i].id, merchantListSZ[i].name) + '">' + merchantListSZ[i].name + '</a></li>');
    }

    for(var i = Math.round(merchantListSZ.length / 2); i < merchantListSZ.length; i++)
    {
        $("#all_merchants_s-z .all_merchants_right_col ul").append('<li><a href="' + buildMerchantURL(merchantListSZ[i].id, merchantListSZ[i].name) + '">' + merchantListSZ[i].name + '</a></li>');
    }
}

// added for printable Offer pages 10/19/07
// modified initOfferPrintable 09/08/09

function initOfferPrintable(){
	var params = location.search;

	if (params.indexOf("printable=yes") != -1) {
		var nParams = "";
		if (params.indexOf("it=") != -1)  {
			nParams = ( params.substring(0,(params.indexOf("it=")-1)) );
		} else {
			nParams = (params.substring(0,(params.indexOf("printable=yes")-1)));
		}
		document.getElementById("footerPrintableLink").innerHTML = "<p>Find this page at: http://usa.visa.com" + location.pathname + nParams + "</p>";
		document.getElementById("footerPrintControls").innerHTML = document.getElementById("printControls").innerHTML;
	}
}

function printOffer(){
	var offerPrint = document.getElementById("emailprintModule");
	if (!offerPrint) return false;
	var wherepage = window.location.href;
	if (wherepage.match(/espanol/i))return false;
	else{offerPrint.innerHTML ="<ul><li class='printIcon'><a href='" +wherepage+ "&printable=yes' target='_blank'>Printable page</a></li></ul>";}
}

//popup email form
function pop_email(url) {
	var newwindow;
	newwindow=window.open(url,'name','height=600, width=700, scrollbars=1');
	if (window.focus) {newwindow.focus()}
}

//popup facebook form
function pop_facebook(url) {
	var newwindow;
	newwindow=window.open(url,'name','height=768,width=1024');
	if (window.focus) {newwindow.focus()}
}

//popup bebo form
function pop_bebo(url) {
	var newwindow;
	newwindow=window.open(url,'name','height=768,width=1024');
	if (window.focus) {newwindow.focus()}
}

$.preloadImages = function() {
	for(var i = 0; i<arguments.length; i++) {
		$("<img>").attr("src", arguments[i]);
	}
};

function init() {
	initOfferPrintable();
	printOffer();
}

window.onload = init;