// define global properties
facebookAppId = '116656235104618';
yhst = "yhst-12207172810064";
domainurl = "http://www.daisy-days.com"; // example "http://www.allvintagegames.com"
facebookpage = "http://www.daisy-days.com/facebook-items.html?fb=1" // facebook page url on site.
$storename = "Daisy Days"; // 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.daisy-days.com/privacy-policy.html";
copyrightId = ".copyright";
badgesId = "";
contentsIdentity = "#section-caption";
hasYMiniCart = false;
hasSCMiniCart = false; // will only clone item #'s and order total area.
shoppingcartHtml = "<a href='"+viewcarturl+"'><img src='//lib.store.yahoo.net/lib/"+yhst+"/fbviewcart.jpg' border='0' /></a>"; // use if hasYMiniCart = false;
contentsTableId = "#contents-table";
contentsTableImgTdId = ".imgCell"
contentsTableInfoTdId = ".infoCell";

haspaging = false; // paging 2.0 only.
pagingTableId = "#contents";
pagingTableImgTd = ".imgCell"
pagingTableInfoTd = ".infoCell";
hasTabbedInfo = false;

// define shell properties
logoimage = "//lib.store.yahoo.net/lib/"+yhst+"/fblogo.jpg"; // use //www. to call the image NOT http://
headHTML = "<a href='http://twitter.com/#!/daisydaysfavors' target='_blank' class='fbtwitter'><img src='//lib.store.yahoo.net/lib/"+yhst+"/fbtwitter.jpg' alt='find us on twitter' border='0' /></a><form id='searcharea' action='http://search.store.yahoo.net/yhst-12207172810064/cgi-bin/nsearch' method='get'><input type='text' id='query' size='12' name='query'><input type='image' id='searchsubmit' class='ys_primary' value='Go' src='//lib.store.yahoo.net/lib/yhst-12207172810064/search-btn.gif' name='searchsubmit'><input type='hidden' value='yhst-12207172810064' name='vwcatalog'></form>"; // use for open html area in the head (phone number, etc).

// define homepage properties
captionheader = ""; // caption description header (item page).
categoriesheader = "<img src='//lib.store.yahoo.net/lib/yhst-12207172810064/fbcatsheader.jpg' alt='facebook products' />"; // categories header (home page).
itemheader = "<img src='//lib.store.yahoo.net/lib/yhst-12207172810064/fbproductsheader.jpg' alt='facebook products' />";

// define section properties
sectionCaptionId = "#section-caption"; // .sectinfo on yahoo, .sectioncontain on scec
sectionPageHeadId = "#page-headline"; // section page header id

// define item page properties
itemdescheader = "Product Description";
crosssellheader = "You May Also Like";
productTableId = "#pit-div";
imageAreaId = "#scMainImage";
mainImgId = "#scMainImgId";
itemNameId = "#page-headline"; // if name is part of the PIT, leave blank.
itemDescId = "#caption-text";

//info page properties
infoPageId = "#info-div";

// define cart properties
cartId = "#ys_pageBody";

pageType = -1;


/* jScale Image Scaler v1.01
* Last updated: Aug 6th, 2009: Fixed bug when "ls (largest side)" option is used
* Author: JavaScript Kit at http://www.javascriptkit.com/
* Visit http://www.javascriptkit.com/script/script2/jScale/ for full source code
*/

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);
}


if(haspaging){
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,appendTo,tablename,isPaging){
	if(isPaging){
		$imgCellTd = $(tableId + " td" + pagingTableImgTd);
		infoCellTd = $(tableId + " td" + pagingTableInfoTd).get();
	} else {
		$imgCellTd = $(tableId + " td" + contentsTableImgTdId);
		infoCellTd = $(tableId + " td" + contentsTableInfoTdId).get();
	}
	
	$contentsrow = "";
	$inforow = "";

	$contents = "<table id='contents-table' class='"+tablename+"' width='100%'></table>"
	$(appendTo).append($contents);
	
	$imgCellTd.each(function(i){
		$i = i;
		$lencount = $i % 3;
		
		$imgCell = $(this).html();
		$infoCell = $(infoCellTd[i]).html();
		
		$contentsrow += "<td class='imgCell scpimgcell'>" + $imgCell + "</td>";
		$inforow +=  "<td class='infoCell scpinfocell'>" + $infoCell + "</td>";
		
		if($lencount != 2){$contentsrow += "<td class='verticalSpacer'>&nbsp;</td>";$inforow += "<td class='verticalSpacer'>&nbsp;</td>";}
		
		if($lencount == 2){
			$("."+tablename).append("<tr>"+$contentsrow+"</tr>");
			$("."+tablename).append("<tr>"+$inforow+"</tr><tr><td class='horizontalSpacer' colspan='10'>&nbsp;</td></tr>");
			$contentsrow = "";
			$inforow = "";
		}
	})
	
	if($contentsrow != ""){
		$("."+tablename).append("<tr>"+$contentsrow+"</tr>");
		$("."+tablename).append("<tr>"+$inforow+"</tr>");
	}

	$("."+tablename).append("</table>");
}

// mailing list html code (copy from store) -- replace this.value with this.value = \'\'
mailinglisthtml = '';

//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>';
			// 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="http://www.daisy-days.com/about.html">About Us</a></li>';
					facebookheader += '<li><a href="http://www.daisy-days.com/contact-us.html">Contact Us</a></li>';
					facebookheader += '<li><a href="'+domainurl+'" target="_blank" class="fbviewsite">Visit Our Site</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 Policy</a>';
			facebookfooter += '<div id="fbfooter-links">';
				facebookfooter += '<ul>';
					facebookfooter += '<li><a href="'+facebookpage+'">Home</a></li>';
					facebookfooter += '<li><a href="http://www.daisy-days.com/about.html">About Us</a></li>';
					facebookfooter += '<li><a href="http://www.daisy-days.com/contact-us.html">Contact Us</a></li>';
					facebookfooter += '<li><a href="'+viewcarturl+'">Shopping Cart</a></li>';
				facebookfooter += '</ul>';
			facebookfooter += '</div>';
			//copyright container
			facebookfooter += '<div class="fbbadges"></div>';

			/* End Custom Area */
			
		facebookfooter += '</div>';
	facebookfooter += '</div>';
			facebookfooter += '<div class="fbcopyright"> &copy; 2004-2011 Daisy Days LLC  -  All Rights Reserved. <span class="designby"><a onclick="window.open(this.href); return false;" href="http://www.solidcactus.com">Website</a> by Solid Cactus.com</span></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 contents"></div>';	
	facebookhomehtml += '</div>';
	facebookhomehtml +='<div class="fbprods">';
	  facebookhomehtml +='<div class="fbheader">';
		  facebookhomehtml +=itemheader;
	  facebookhomehtml +='</div>';
	  facebookhomehtml +='<div id="facebookcontent" class="contents"></div>';
	facebookhomehtml +='</div>';
facebookhomehtml +='</div>';
facebookhomehtml +='<div id="fbiteminfocontain" style="display:none;"></div>';
facebookhomehtml +='<div id="homefbbadges"></div>';
facebookhomehtml +='<div id="homefbtext" 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" class="contents"></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 || $("#contact-img").length > 0) { pageType = 4; }
        if ($(pagingTableId).length > 0) { pageType = 5; }

        mylocation = window.location.toString();
        if (mylocation.indexOf("search.store.yahoo.net") > -1) {
            pageType = 6;
        }

        //alert(pageType);

        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);
                $("#homefbtext").html($captiondiv.html());
                $("#homefbtext").show();
            } else {
                $("#fbmessage").hide();
            }
            // find items and categories
            if ($(".products").length > 0) { writeContentsTable(".products", "#facebookcontent", "fbprodtable", false) } else { $(".fbprods").hide(); }
            if ($(".categories").length > 0) { writeContentsTable(".categories", ".fbcategories", "fbcatstable", false) } else { $(".fbcats").hide(); }

            // banner image
            prodImage = $(".homebanner").clone(true);
            $('.fbbanner').prepend(prodImage);

            $("#homefbbadges").html("<img src='//lib.store.yahoo.net/lib/" + yhst + "/fbbadges.jpg' alt='' border='0' />");

            page_name = "Home Page";
        }


        // section page
        if (pageType == 1 || pageType == 5) {
            $('body').append(facebookhtml);

            subhead = $(sectionPageHeadId).clone(true);
            $('#fbcont-int').prepend(subhead);

            if ($(sectionCaptionId).length > 0) {
                $captiondiv = $(sectionCaptionId).clone(true);
                $("#facebookcaption").html($captiondiv.text());
            } else {
                $("#fbmessage").hide();
            }

            // hide items that don't belong
            $(".fbbanner").hide();
            $("#fbmessage img").hide();
            $(".fbdescheader").hide();
            $(".fbheader").hide();

            // find items and categories
            if ($(contentsTableId).length > 0) {
                writeContentsTable(contentsTableId, "#facebookcontent", "fbsectiontable", false)
            } else if ($(pagingTableId).length > 0) {
                writeContentsTable(pagingTableId, "#facebookcontent", "fbsectiontable", true)
            } else {
                $(".fbprods").hide();
            }
            page_name = "Section Page";
        }

        // item page
        if (pageType == 2) {

            $('body').append(facebookitem);

            if ($(imageAreaId).length > 0) {
                prodImage = $(imageAreaId).clone(true);
            } else if ($(imageAreaId).length < 1 && $(mainImgId).length > 0) {
                prodImage = $(mainImgId).clone(true);
            }

            $('.fbleft').prepend(prodImage);
            $(".fbleft img#scMainImgId").jScale({ w: '180px' });
            $(".fbleft img#scMainImgId").jScale({ h: '200px' });

            infoTable = $(productTableId).clone(true);
            $('.fbright').append(infoTable);

            if (itemNameId != "") {
                itemnametxt = $(itemNameId + ":first").text();
                $('.fbitemname').text(itemnametxt);
            }

            // item description
            if (hasTabbedInfo) {
                itemDesc = $(".tabinfomain").clone(true);
                $(".fbitemdesctxt").append(itemDesc);
                $(".tabinfomain").tabbedInfo({ firetab: 0 });
                $(".fbitemdesctxt .tabinfo:first").attr("style", "");
                $(".fbitemdesctxt .tabbtns:first").click();
                $(".tabbtns:contains('build your own')").hide();
                $(".tabbtns:contains('reviews')").hide();
            } else {
                // item description
                $(".fbitemdesctxt").html($(itemDescId).html());
                $("embed, object").attr("width", "490");
            }

            // cross sell
            if ($(contentsTableId).length > 0) {
                writeContentsTable(contentsTableId, "#fbcsitems", "fbitemtable", false)
            } 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);

            $("#ys_pageMessage img").hide();
            page_name = "Cart Page";
        }

        // info page
        if (pageType == 4) {
            $('body').append(facebookhtmlcart);

            $infoHtml = $(infoPageId).clone(true);
            $("#fbcont-int").html($infoHtml);

            if ($("#contact-img").length > 0) {
                $infoHtml = $("#body-pad table:first").clone(true);
                $("#fbcont-int").html($infoHtml);
                $("#fbcont-int").prepend("<div id='page-headline'>Contact Us</div>");
                $("#fbcont-int").attr("style", "padding-left:20px;");
            }

            if ($("form").length > 0) {
                $("form").append("<input type='hidden' name='Source' value='Facebook' />");
            }
            page_name = "Info Page";
        }
        if (pageType == 6) {
            $('body').append(facebookhtmlcart);
            cloneform = $("form[name='vw-form']").clone(true);

            $("#fbcont-int").html(cloneform);
        }
        // default
        if (pageType == -1) {
            $('body').append(facebookhtmlcart);
            $("#fbcont-int").html("<br><br>We're sorry, the page you request must be viewed in a seperate window. <a href='" + window.location.href + "' target='_blank'>Click Here</a> if the new window did not open. The items that are currently in your cart will be found in the new window as well.<br><br>");
            open(window.location.href);
        }

        // clean up headers that do not have information incase styles were applied
        $(".fbheader").each(function () {
            if ($(this).text() == "" && $(this).html() == "") {
                $(this).hide();
            }
        });

        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);
        }

        //clone default items

        // 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);
        } ());

    }
});


