// define global properties
facebookAppId = '158740354213405';
yhst = "yhst-39130775443729";
domainurl = "http://www.heartratemonitorsusa.com"; // example "http://www.allvintagegames.com"
facebookpage = "http://www.heartratemonitorsusa.com/facebook-items.html" // facebook page url on site.
storename = "Heart Rate Monitors USA"; // Store name
viewcarturl = "http://order.store.yahoo.net/"+yhst+"/cgi-bin/wg-order?" + yhst;
cssLocation = "//lib.store.yahoo.net/lib/"+yhst+"/facebook-styles-yahoo.css";
privacyLink = "http://www.heartratemonitorsusa.com/privacy-policy.html";
copyrightId = ".credits";
badgesId = "";
contentsIdentity = ".sectcontents";
hasYMiniCart = false;
hasSCMiniCart = false;
shoppingcartHtml = "<a href="+viewcarturl+"><img src='//lib.store.yahoo.net/lib/"+yhst+"/fbcart.jpg' border='0' /></a>"; // use if hasYMiniCart = false;
contentsTableId = "#contents-table";
contentsTableImgTdId = ".imgCell"
contentsTableInfoTdId = ".infoCell";




// define shell properties
logoimage = "//lib.store.yahoo.net/lib/"+yhst+"/fblogo.jpg"; // use //www. to call the image NOT http://
headHTML = '<img border="0" alt="Follow us on Twitter" src="//lib.store.yahoo.net/lib/'+yhst+'/fbhtml1.jpg" class="html1"><img border="0" alt="Follow us on Twitter" src="//lib.store.yahoo.net/lib/'+yhst+'/fbhtml2.jpg" class="html2"><ul class="fbtopnav"><li><a href="http://www.heartratemonitorsusa.com/heramo.html">Heart Rate Monitors</a></li><li><a href="http://www.heartratemonitorsusa.com/blood-pressure.html">Blood Pressure Machines</a></li><br /><li class="third"><a href="http://www.heartratemonitorsusa.com/hydration.html">Hydration Products</a></li><li><a href="http://www.heartratemonitorsusa.com/wellness.html">Wellness Products</a></li><li><a href="http://www.heartratemonitorsusa.com/coolstuff.html">Electronics</a></li></ul>'; // use for open html area in the head (phone number, etc).

// define homepage properties
captionheader = ""; // caption description header (item page).
categoriesheader = ""; // categories header (home page).
itemheader = "";

// define section properties
sectionCaptionId = ".sectinfocont"; // .sectinfo on yahoo, .sectioncontain on scec
sectionPageHeadId = ".pagename"; // section page header id
pagingTableId = "#scpContents";
rewriteSectionContents = false;
rewritePagingContents = false;

// define item page properties
itemdescheader = "Product Description";
crosssellheader = "You May Also Like";
productTableId = ".pit-of";
imageAreaId = "#scMainImage";
itemNameId = ".pagename"; // if name is part of the PIT, leave blank.
itemPageCaptionId = ".tabinfo:first";

//info page properties
infoPageId = "#info-div";

// define cart properties
cartId = "#ys_pageBody";

pageType = "";

jQuery.jScale={
	getnewSize:function(side, nvalue){
		var otherside=(side=="w")? "h" : "w"
		if (typeof nvalue=="undefined" || nvalue==null) //if this side has no explicit size set, scale it
			var newSize=this.ndimensions[otherside] * this.odimensions[side] / this.odimensions[otherside]
		else
			var newSize=(/%/.test(nvalue))? parseInt(nvalue)/100 * this.odimensions[side] : parseInt(nvalue)
		this.ndimensions[side]=Math.round(newSize)
	},
	getnewDimensions:function($, imgref, setting, callback){
 		//create temporary floating image to get original image's true dimensions (in case width/height attr set)
		var $tempimg=$('<img src="'+imgref.src+'" style="position:absolute; top:0; left:0; visibility:hidden" />').prependTo('body')
		this.odimensions={w:$tempimg.width(), h:$tempimg.height()} //get image dimensions
		var sortbysize=(this.odimensions.w>this.odimensions.h)? ["w","h"] : ["h","w"] //array to determine [largerside, shorterside]
		this.ndimensions={}
		if (typeof setting.ls!="undefined"){ //if setting.ls defined
			setting[sortbysize[0]]=setting.ls //set the correct side to the longest side's value setting
			setting[sortbysize[1]]=null
		}
		var sortbyavail=(setting.w)? ["w","h"] : (setting.h)? ["h","w"] : [] //check which side to work on based on availibility (which property is set by user)
		if (sortbyavail.length>0){
			this.getnewSize(sortbyavail[0], setting[sortbyavail[0]]) //work on side with property that's defined for sure first
			this.getnewSize(sortbyavail[1], setting[sortbyavail[1]]) //work on side with property that may or may not be defined last
			var callbackfunc=callback || function(){}
			if (setting.speed>0)
				$(imgref).animate({width:this.ndimensions.w+'px', height:this.ndimensions.h+'px'}, setting.speed, callbackfunc)
			else{
				$(imgref).css({width:this.ndimensions.w+'px', height:this.ndimensions.h+'px'})
				callbackfunc.call(imgref)
			}
		}
		$tempimg.remove()
	}
};

jQuery.fn.jScale=function(setting, callback){
	return this.each(function(){ //return jQuery obj
		var imgref=this
		if (typeof setting=="undefined" || imgref.tagName!="IMG")
			return true //skip to next matched element
		if (imgref.complete){ //account for IE not firing image.onload
			jQuery.jScale.getnewDimensions(jQuery, imgref, setting, callback)
		}
		else{
			$(this).bind('load', function(){
				jQuery.jScale.getnewDimensions(jQuery, imgref, setting, callback)
			})
		}
	})
};

// Write stylesheet if inside of facebook
if (window.parent!==window.self && self.name.indexOf("app_runner_")==0 || typeof(fbtesting) !== "undefined"){
	var headID = document.getElementsByTagName("head")[0];         
	var cssNode = document.createElement('link');
	cssNode.type = 'text/css';
	cssNode.rel = 'stylesheet';
	cssNode.href = cssLocation;
	cssNode.media = 'screen';
	headID.appendChild(cssNode);
}

function findProducts(isSection){
		if(isSection){$contentsdiv = $("#contents-table").clone(true);} else {$contentsdiv = $(".products").clone(true);}
		$("#facebookcontent").html($contentsdiv);
}

function findCategories(){
	$cats = $(".categories").clone(true);
	$(".fbcategories").html($cats);
}

function changePagingProps() {
	if(window.scPaging!=undefined){
		scPaging.addEvent("onInit",function() {
			scPaging.itemsPerPageText="all";	
			scPaging.calculateItemsPerPage();
			scPaging.calculateTotalPages();
		});
	}
}

// if paging 2.0 is detected.
if (window.parent!==window.self && self.name.indexOf("app_runner_")==0 || typeof(fbtesting) !== "undefined"){
	changePagingProps();
}

function writeContentsTable(tableId){
	$imgCellTd = $(tableId + " td" + contentsTableImgTdId);
	infoCellTd = $(tableId + " td" + contentsTableInfoTdId).get();
	$contentsrow = "";
	$inforow = "";

	$contents = "<table id='contents-table' class='fbContentsTable' width='100%'></table>"
	$("#facebookcontent").append($contents);
	
	$imgCellTd.each(function(i){
		$i = i;
		$lencount = $i % 3;
		
		$imgCell = $(this).html();
		$infoCell = $(infoCellTd[i]).html();
		
		$contentsrow += "<td class='imgCell'>" + $imgCell + "</td>";
		$inforow +=  "<td class='infoCell'>" + $infoCell + "</td>";
		
		if($lencount != 2){$contentsrow += "<td class='verticalSpacer'>&nbsp;</td>";$inforow += "<td class='verticalSpacer'>&nbsp;</td>";}
		
		if($lencount == 2){
			$(".fbContentsTable").append("<tr>"+$contentsrow+"</tr>");
			$(".fbContentsTable").append("<tr>"+$inforow+"</tr><tr><td class='horizontalSpacer' colspan='10'>&nbsp;</td></tr>");
			$contentsrow = "";
			$inforow = "";
		}
	})
	
	if($contentsrow != ""){
		$(".fbContentsTable").append("<tr>"+$contentsrow+"</tr>");
		$(".fbContentsTable").append("<tr>"+$inforow+"</tr>");
	}

	$contents += "</table>";
	
	
}

// mailing list html code (copy from store) -- replace this.value with this.value = \'\'
mailinglisthtml = '<div class="newsdesc">Join our mailing list to receive the latest news & info!</div><div class="twittericon"><a href="#"><img border="0" onclick="MM_openBrWindow(\'http://twitter.com/HRM_USA\',\'Twitter\',\'status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=1000,height=400\')" alt="Follow us on Twitter" src="/lib/yhst-39130775443729/fbtwitter.jpg"></a></div><form name="form1" action="https://www.mcssl.com/app/contactsave.asp" method="post"><input type="text" id="newsletter-email" value="enter email address" onblur="if(this.value == \'\'){this.value= this.defaultValue;}" onfocus="if(this.value == this.defaultValue){this.value=\'\';}" name="Email1"><input type="image" name="cmdSubmit" alt="Newsletter Submit" src="/lib/yhst-39130775443729/mailing-go.jpg" id="newsletter-go" value="Go!"><input type="hidden" value="178158" id="merchantid" name="merchantid"><input type="hidden" value="http://www.heartratemonitorsusa.com/newsletter-thank-you.html" id="ARThankyouURL" name="ARThankyouURL"><input type="hidden" value="0" id="copyarresponse" name="copyarresponse"><input type="hidden" value="0" id="custom" name="custom"><input type="hidden" value="556708" id="defaultar" name="defaultar"><input type="hidden" value="0" id="allowmulti" name="allowmulti"><input type="hidden" value="Email1" id="visiblefields" name="visiblefields"><input type="hidden" value="Email1" id="requiredfields" name="requiredfields"></form>';

//shell header
facebookheader = '<div id="fb-root">';
	// shell start
	facebookheader += '<div id="page">';
		// header area start
		facebookheader += '<div id="fbheader">';
			facebookheader += '<div class="fbheadhtml">'+headHTML+'</div>';
			facebookheader += '<a href="'+facebookpage+'" id="logolink">';
				// logo image
				facebookheader += '<img src="'+logoimage+'" alt="'+storename+'" title="'+storename+'" border="0" />';
			facebookheader += '</a>';
			// cart container
			if(hasYMiniCart){
				facebookheader += '<div class="fbcart"></div>';
			} else {
				facebookheader += '<div class="fbcart">'+shoppingcartHtml+'</div>';
			}
			   
			   
			
			// header links
			facebookheader += '<div id="fbheader-links">';
				facebookheader += '<ul>';
					facebookheader += '<li><a href="'+facebookpage+'">Home</a></li>';
					facebookheader += '<li><a href="'+domainurl+'" target="_blank">Visit Our Site</a></li>';
					facebookheader += '<li><a href="'+viewcarturl+'">View Cart</a></li>';
				facebookheader += '</ul>';
			facebookheader += '</div>';
		facebookheader += '</div>';
		// header area end
		facebookheader += '<div id="fbcontent">';

// shell footer
		facebookfooter = '</div>';
		facebookfooter += '<div id="fbfooter">';
			facebookfooter += mailinglisthtml;
			facebookfooter += '<a href="'+privacyLink+'" id="fb-privacy">Privacy Respected</a>';
			facebookfooter += '<div id="fbfooter-links">';
				facebookfooter += '<ul>';
					facebookfooter += '<li><a href="'+facebookpage+'">Home</a></li>';
					facebookfooter += '<li><a href="'+domainurl+'" target="_blank">Visit Our Site</a></li>';
					facebookfooter += '<li><a href="'+viewcarturl+'">View Cart</a></li>';
				facebookfooter += '</ul>';
			facebookfooter += '</div>';
			//copyright container
			facebookfooter += '<div class="fbcopyright"></div>';
			facebookfooter += '<div class="fbbadges"></div>';

			/* End Custom Area */
			
		facebookfooter += '</div>';
	facebookfooter += '</div>';
facebookfooter += '</div>';

// home/section page body
facebookhomehtml ='<div id="fbcont-int">';
	// banner area
	facebookhomehtml +='<div class="fbbanner pagebanner">';
	facebookhomehtml +='</div>';
	facebookhomehtml +='<div id="fbmessage">';
		facebookhomehtml +='<div class="fbheader">';
			facebookhomehtml += captionheader;
		facebookhomehtml += '</div>';
		// caption container
		facebookhomehtml +='<div id="facebookcaption"></div>';
	facebookhomehtml +='</div>';
	facebookhomehtml +='<div class="fbcats">';
		// categories header
		facebookhomehtml +='<div class="fbheader">';
			facebookhomehtml += categoriesheader;
		facebookhomehtml += '</div>';
		// categories container
		facebookhomehtml +='<div class="fbcategories"></div>';	
	facebookhomehtml += '</div>';
	facebookhomehtml +='<div class="fbprods" id="scPaging">';
	  facebookhomehtml +='<div class="fbheader">';
		  facebookhomehtml +=itemheader;
	  facebookhomehtml +='</div>';
	  facebookhomehtml +='<div id="facebookcontent"></div>';
	facebookhomehtml +='</div>';
facebookhomehtml +='</div>';
facebookhomehtml +='<div id="fbiteminfocontain" style="display:none;"></div>';
facebookhtml = facebookheader + facebookhomehtml + facebookfooter;

// item page html
facebookitemhtml ='<div id="fbcont-int">';
  if(itemNameId != ""){
  	facebookitemhtml += '<div class="fbitemname"></div>';
  }
  facebookitemhtml +='<div class="fbitemcontain">';
      facebookitemhtml +='<div class="fbleft"></div>';
      facebookitemhtml +='<div class="fbright"></div>';
  facebookitemhtml +='</div>';
  facebookitemhtml +='<div class="fbitemdesc clear">';
      facebookitemhtml +='<div class="fbheader">'+itemdescheader+'</div>';
      facebookitemhtml +='<div class="fbitemdesctxt"></div>';
  facebookitemhtml +='</div>';
  facebookitemhtml +='<div class="fbcrossell">';
      facebookitemhtml +='<div class="fbheader">'+crosssellheader+'</div>';
      facebookitemhtml +='<div id="fbcsitems"></div>';
  facebookitemhtml +='</div>';
  /*facebookitemhtml +='<div class="fbrelated">';
      facebookitemhtml +='<div class="fbheader">'+relatedcatsheader+'</div>';
      facebookitemhtml +='<div id="fbrelatedcats"></div>';
  facebookitemhtml +='</div>';
  */
facebookitemhtml +='</div>';
facebookitem = facebookheader + facebookitemhtml + facebookfooter;

// cart body html
facebookhtmlcart = facebookheader + '<div id="fbcont-int"></div>' + facebookfooter;

$(document).ready(function () {
    if (window.parent !== window.self && self.name.indexOf("app_runner_") == 0 || typeof (fbtesting) !== "undefined") {
        // determine what type of page it is and run correct code.
        // 0 = home, 1 = section, 2 = item, 3 = cart, info = 4

        //remove snapshop init class
        $(".popImg-0036").attr("class", "");

        if (location.href == facebookpage || typeof (fbtesting) !== "undefined") { pageType = 0; }
        if (location.href != facebookpage && $(productTableId).length < 1 && $(contentsIdentity).length > 0 && typeof (fbtesting) === "undefined") { pageType = 1; }
        if ($(productTableId).length > 0) { pageType = 2; }
        if ($(cartId).length > 0) { pageType = 3; }
        if ($(infoPageId).length > 0) { pageType = 4; }
        if ($(pagingTableId).length > 0) { pageType = 5; }

        var page_name = "Default Page";

        // homepage
        if (pageType == 0) {
            // append the home html
            $('body').append(facebookhtml);

            // grab the text
            if ($(sectionCaptionId).length > 0) {
                $captiondiv = $(sectionCaptionId).clone(true);
                $("#facebookcaption").html($captiondiv.html());
            } else {
                $("#fbmessage").hide();
            }
            // find items and categories
            if ($(".products").length > 0) { findProducts(false); } else { $(".fbprods").hide(); }
            if ($(".categories").length > 0) { findCategories(false); } else { $(".fbcats").hide(); }

            // banner image
            prodImage = $(".homebanner").clone(true);
            $('.fbbanner').prepend(prodImage);

            page_name = "Home Page"
        }


        // section page
        if (pageType == 1 || pageType == 5) {
            $('body').append(facebookhtml);

            subhead = $(sectionPageHeadId).clone(true);
            $('#fbcont-int').prepend(subhead);

            // Custom
            if ($("#viewmore").length > 0) {
                $("#viewmore").click();
            }

            if ($(sectionCaptionId).length > 0) {
                $captiondiv = $(sectionCaptionId).clone(true);
                $("#facebookcaption").html($captiondiv.text());
            } else {
                $("#fbmessage").hide();
            }

            // view more feature for text
            /*
            var capcont = $("#facebookcaption " + sectionCaptionId);
            if (capcont.get(0)) {
            var captext = capcont.get(0).innerHTML;
            var captlen = captext.length;
            if(captlen>390){
            var captslice = captext.slice(0,390) + "... </b></p><span id='viewmore'> view more</span>";
            capcont.html(captslice);
            }
				
            $("#facebookcaption #viewmore").click(function(){
            var old=$("#facebookcaption #sectinfocont-inner")[0];
            $(old).before("<div id='sectinfocont-inner'>"+captext+"</div>");
            $(old).remove();
            });
            }
            */

            // hide items that don't belong
            $(".fbbanner").hide();
            $("#fbmessage img").hide();
            $(".fbdescheader").hide();
            $(".fbheader").hide();


            // write contents or find paging.
            if (pageType == 1) {
                if (rewriteSectionContents) {
                    writeContentsTable(contentsTableId)
                } else if ($(contentsTableId).length > 0) {
                    $contentsClone = $(contentsTableId).clone(true);
                    $(".fbprods").html($contentsClone);
                } else {
                    $(".fbprods").hide();
                }
            } else if (pageType == 5) {
                if (rewritePagingContents) {
                    writeContentsTable(pagingTableId, "#facebookcontent", "fbsectiontable", true);
                    $(".scpimg a").attr("style", "display:block;");
                } else if ($(pagingTableId).length > 0) {
                    $contentsClone = $(pagingTableId).clone(true);
                    $(".fbprods").html($contentsClone);

                    /* custom */
                    $(".scpimg img").jScale({ w: '150px' });

                }
            } else {
                $(".fbprods").hide();
            }
            page_name = "Section Page";
        }

        // item page
        if (pageType == 2) {

            $('body').append(facebookitem);

            prodImage = $(imageAreaId).clone(true);
            $('.fbleft').prepend(prodImage);

            infoTable = $(productTableId).clone(true);
            $('.fbright').append(infoTable);

            $(".fbleft img#scMainImgId").jScale({ w: '180px' });
            $(".fbleft img#scMainImgId").jScale({ h: '200px' });

            if (itemNameId != "") {
                itemnametxt = $(itemNameId + ":first").html();
                itemnametxt = itemnametxt.toString().replace("<br>", "").replace("<br />")
                $('.fbitemname').html(itemnametxt);
            }

            // item description
            $(".fbitemdesctxt").html($(itemPageCaptionId).html());

            // cross sell
            if ($(".upsell-panel").length > 0) {
                relitems = $(".upsell-panel").clone(true);
                $('#fbcsitems').append(relitems);
            } else {
                $(".fbcrossell").hide();
            }
            page_name = "Item Page";
        }

        // cart
        if (pageType == 3) {
            $myelement = $(cartId).clone(true);

            $('body').append(facebookhtmlcart);
            $("#fbcont-int").html($myelement);
            $("#fbcont-int").css("padding", "0");

            $("a[href='http://store.yahoo.com/" + yhst + "/index.html']").attr("href", facebookpage);

            page_name = "Cart Page";
        }

        if (pageType == 4) {
            $('body').append(facebookhtmlcart);

            $infoHtml = $(infoPageId).clone(true);
            $("#fbcont-int").html($infoHtml);
            page_name = "Info Page";
        }

        // info page

        var trackerName = "~0";
        if (window._gat && window._gat._getTrackerByName(trackerName) && window._gat._getTrackerByName(trackerName)._trackEvent) {
            window._gat._getTrackerByName(trackerName)._setCustomVar(1, "Face Book Store", page_name, 3);
            window._gat._getTrackerByName(trackerName)._trackEvent("FaceBook Store", "Open", page_name, 0);
        }

        // clean up headers that do not have information incase styles were applied
        $(".fbheader").each(function () {
            if ($(this).text() == "" && $(this).html() == "") {
                $(this).hide();
            }
        });

        //clone default items

        // badges
        if (badgesId != "") {
            badgehtml = $(badgesId).html();
            $(".fbbadges").html(badgehtml);
        }
        // copy right
        if (copyrightId != "") {
            copyhtml = $(copyrightId).html();
            $(".fbcopyright").html(copyhtml);
        }

        // floating cart
        if (hasYMiniCart || hasSCMiniCart) {
            window.checkIntervalId = window.setInterval(function () {
                if ($("#toggLink-0061").length > 0) {
                    cartpage = $("#minCart-0061").clone(true);
                    $('.fbcart').html(cartpage);
                    //$('.fbcart').click(function(){window.location = viewcarturl;});
                    window.clearInterval(window.checkIntervalId);
                }

                // yMiniCart
                if ($("#yfc_mini").html() != "") {
                    cartpage = $("#yfc_mini").clone(true);
                    $('.fbcart').append(cartpage);
                    $('.fbcart').click(function () { window.location = viewcarturl; });
                    window.clearInterval(window.checkIntervalId);
                }
            }, 500);
        }

        /* ------------------------------------------------------------ Custom ------------------------------------------------ */

        // facebook code to resize iFrame
        window.fbAsyncInit = function () {
            //Your app details here
            FB.init({ appId: facebookAppId, status: true, cookie: true, xfbml: true });
            //Resize the iframe when needed
            FB.Canvas.setAutoResize();
            FB.Canvas.scrollTo(0, 0);
        };
        //Load the SDK asynchronously
        (function () {
            var e = document.createElement('script'); e.async = true;
            e.src = document.location.protocol +
			  '//connect.facebook.net/en_US/all.js';
            document.getElementById('fb-root').appendChild(e);
        } ());

    }
});
