// JavaScript Document

/*
Class: TestimonyPopUp
2008 Nov 13
It manage the pop-up which show the details of the little testimony module on
cart_product_detail.php
*/
var TestimonyPopUp=function()
{
	//Properties
	this.popUp=null;
	this.tstm_id = null;
	this.processorUrl = null;
	this.product_name = null;
	
	this.muestrame_success = function(o)
	{
		var view = YAHOO.lang.JSON.parse(o.responseText);
		//alert(view[0]["hd"]);
		this.popUp.setHeader(view[0]["hd"]);
		this.popUp.setBody(view[0]["bd"]);
		this.popUp.setFooter(view[0]["ft"]);
		this.popUp.render(document.body);	
		this.popUp.show();
		$(".lightbox").lightbox();
	}
	
	this.muestrame_failure = function()
	{
		alert("Error in muestrame function");	
	}
	
	this.muestrame = function(tstm_id)
	{
	
		var callBack=
		{
			success: this.muestrame_success,
			failure: this.muestrame_failure,
			scope: this
		};
		var postData = "action=pop&tstm_id="+tstm_id;
		//YAHOO.util.Dom.get(this.storedAddressesDiv).innerHTML= ("<p>Loading ...<p>");
		YAHOO.util.Connect.asyncRequest('POST', this.processorUrl, callBack, postData);	
	}
	this.mask_click = function(e, obj)
	{
		this.popUp.hide();
		this.popUp.render(document.body);	
	}
	/*
	Function: init
	it plays the roles of the constructor, but you have to call it explicity.
	*/
	this.init=function()
	{
		//this.tstm_array = eval(resultado);
		//alert(this.tstm_array["tstm_all_testimony"]);
		this.processorUrl =	"../model/cart_product_detail_MDL.php";
		this.popUp = new YAHOO.widget.Panel("testimonyWindow_pnl", {
																		width:"620px", 
																		//height:"400px",
																		fixedcenter: true, 
																		underlay:"shadow", 
																		close:true, 
																		visible:false, 
																		draggable:true,
																		modal: true
																	});
		
		//YAHOO.lang.JSON.parse
		YAHOO.util.Event.addListener("testimonyWindow_pnl_mask", "click", this.mask_click, this, true);
		this.popUp.render(document.body);
	}
	
}


/*
	Class: MoreViews, 2008 Apr 18
	It provides all the functions to handle Extra Images of a product.
*/
var MoreViews = function()
{
	//PROPERTIES
	//var firstIndex=0;
	//var superIndex = 1;
	/*
	Variable: thumbnail_arr
	Array of thumbnail views (Views -> Extra Images) of the product.
	*/
	var thumbnail_arr = null;
	/*
	Variable: medium_arr
	Array of medium size views (Views -> Extra Images) of the product.
	*/
	var medium_arr = null;
	/*
	Variable: thumbnail_arr
	Array of primary views (Views -> Extra Images) of the product.
	*/
	var primary_arr = null;
	var site_url = null; 
	var product_id = null;
    var category_id = null;
	var product_url = null;
	this.product_name = null;


	/*
	Note: Jan 13 2009
	This function returns the name of the image for the alt property with the extension, underscores and hyphens removed
	*/
	
	this.getOneItemImage_getAlt = function(data_string)
	{
		var alt_string = new String();
		
		alt_string = data_string;
		alt_string = alt_string.replace(/_/g," ");
		alt_string = alt_string.replace(/-/g," ");
		alt_string = alt_string.replace(/.jpg/g,"");
		alt_string = alt_string.replace(/'/g,"&acute;");
		
		return alt_string;
	}
	
	/*
	Note: 2009 JAn 13
	This function returns alt attribute of each images.
	*/
	this.setAltAttribute = function(altImage)
	{
		var result = "";
		if(altImage != "")
		{
			splitResult = unescape(altImage).split ("/");
			result = this.getOneItemImage_getAlt(splitResult[splitResult.length-1]);
		}
		return result;
	}
	
	/*
	Note: 2009 Jan 21
	This function was created to add loading gif before the true image appears.
	*/
	
	this.waitForImage = function(loadingImage, setImage, alt, stepDuration)
	{
		var loadingImageHTML = YAHOO.util.Dom.get(loadingImage);
		var setImageHTML = YAHOO.util.Dom.get(setImage);
		if(!setImageHTML.complete){
		var _this = this;
		setTimeout(function() { _this.waitForImage(loadingImage, setImage, alt, stepDuration) }, stepDuration);
			//setTimeout("waitForMainImage("+"\""+alt+"\")", 250);
		}
		else
		{
			YAHOO.util.Dom.removeClass(loadingImageHTML.id, 'elementVisible');
			YAHOO.util.Dom.addClass(loadingImageHTML.id, 'elementHidden');
			YAHOO.util.Dom.removeClass(setImageHTML.id, 'elementHidden');
			YAHOO.util.Dom.addClass(setImageHTML.id, 'elementVisible');
			setImageHTML.setAttribute('alt',alt);
		}
	}

	/*
		Function: rotateViews
		It moves all the views one step to the left.
	*/			
	this.rotateToFirst=function(index)
	{
		this.firstIndex = index;
		if(this.firstIndex==this.thumbnail_arr.length)
			this.firstIndex=0;
		this.placeImages(this.firstIndex);
		this.placeAsMainImage(this.firstIndex);
	}
	/*
		Function: rotateViews
		It moves all the views one step to the left.
	*/			
	this.rotateOneImage=function()
	{
		//if this is the last, we put this.firstIndex in cero because we need to show extra images
		if(this.firstIndex==this.thumbnail_arr.length-1)
			this.firstIndex=0;
		else
			this.firstIndex++;//Here, we move all the Views one step to the left.
		//alert("first index: "+this.firstIndex);
		this.placeImages(this.firstIndex);
		this.placeAsMainImage(this.firstIndex);
	}
	this.placeAsMainImage=function(index)
	{
		//var mainImageHTML = "<a href='#'><img id='mainImage'></a>";
		//show specific medium_image fom cart_product_extra_images table and put primary_arr in <a> 
		//note: 2008 jul 25 add jquery lightbox manually
		var mainImageHTML = "<a rel='lightbox' class='lightbox' href='"+this.primary_arr[index]+"' >";
		//Note: 2010Mar28 - Style in CSS file
		//var mainImageHTML = "<a rel='lightbox' class='lightbox' style='display:block; width:250px; height:auto; overflow:hidden;' href='"+this.primary_arr[index]+"' >";
		mainImageHTML += "<img id='loadingMainImage' class='elementVisible' src='../../site_files/FiftyFlowers/ff_images/mozilla_blu.gif' />";
		mainImageHTML += "<img id='setMainImage' src='"+this.primary_arr[index]+"' class='elementHidden'/> </a>";
		//mainImageHTML += "<img id='setMainImage' src='"+this.medium_arr[index]+"' class='elementHidden' width='250px' /> </a>";
		//alt='"+this.product_name+"'		
		
		//Now we place the HTML content inside "moreViews" div.
		this.showMainPicture.innerHTML = mainImageHTML;
		
		var loadingImage = "loadingMainImage";
		var setImage = "setMainImage";
		var alt = this.setAltAttribute(this.medium_arr[index]);
		var stepDuration = 250;
		/*
		Note: 2009 Jan 21
		This section was created to add loading gif before the main image appears.
		*/
		this.waitForImage(loadingImage, setImage, alt, stepDuration);
		
		
		//this.e.onContentReady('mainImage', this.fadeIn);
		//it's necesary to function lightbox effect
		//Lightbox.init();
		//Slimbox.scanPage();
		//initLightbox();
		//$(".lightbox").lightbox();
		/*
		Note: 2008 august 08
		esta línea es necesaria para que funcione el efecto de lightbox en todas las imágenes incluidas las extra images
		*/
		$(".lightbox").lightbox();
		
	}
	/*
	Function: placeImages
	It inserts three views and the "moreViewsBar" in "moreViews" div.
	*/
	this.placeImages=function(count)
	{
	//Initialize variable
		var moreViewsHTML="";
		var currentIndex = count;
		var j = 0;
		var superIndex = count;
		//create new div to view images
		if (this.thumbnail_arr.length > 1)
		{
			var altAttribute = 0;
			moreViewsHTML+="<div id='views'>";
			while(j!=3 && j!=this.thumbnail_arr.length)
			{
				
				//only print 3 extra images
				//With this we assign a custom style for the last imageBox.
				if(j==2)
				{
					moreViewsHTML+="<div id='imageBox_3' class='imageBox lastBox'>";
				}
				else
				{
					moreViewsHTML+="<div id='imageBox_3' class='imageBox'>";
				}
				/*
				Note: 2008 Oct 08
				la siguiente línea es necesaria para el atributo "alt de las imágenes pequeñas"
				*/
				altAttribute = altAttribute+1;
				//add images in views div
				moreViewsHTML+="<a href='javascript:moreViews.rotateToFirst(\""+currentIndex+"\");'>";
				moreViewsHTML+="<img id='loading_image_"+currentIndex+"' class='elementVisible' src='../site_files/FiftyFlowers/ff_images/mozilla_blu.gif' />";
				moreViewsHTML+="<img id='thumbnail_image_"+currentIndex+"' src='"+this.thumbnail_arr[currentIndex]+"' class='elementHidden' width='75' height='75' />";
				//moreViewsHTML+="<img id='thumbnail_image_"+currentIndex+"' src='"+this.thumbnail_arr[currentIndex]+"' class='elementHidden' width='75' height='75'  />";
				//alt='"+this.product_name+" "+altAttribute+"'
				moreViewsHTML+="</a>";
				moreViewsHTML+="</div>";
				this.alt[currentIndex] = this.setAltAttribute(this.thumbnail_arr[currentIndex]);						
				
				//increment currentIndex to show the next element if the array
				 currentIndex++;				
				 j++;
				 if(currentIndex==this.thumbnail_arr.length)
					currentIndex=0;
				
			};
			moreViewsHTML+="</div>";
		}			
		moreViewsHTML+="<div id='moreViewsBar'>";	
		//If there are more than 3 views (Extra Images) we will display "moreViewsBar"
		if(this.thumbnail_arr.length > 3)
		{
			
			superIndex++;
			moreViewsHTML+="<div>More Images: "+superIndex+"/"+this.thumbnail_arr.length+" <a href='javascript:moreViews.rotateOneImage();'>>></a></div>";
		}
		moreViewsHTML+="<div><a href='"+this.site_url+"/custom.php?name=Email a Friend&amp;id="+this.product_id+"&amp;url="+this.product_url+"' class='emailFriend'>Email</a></div>";
		moreViewsHTML+="<div><a href='javascript:window.print();' class='print'>Print</a></div>";
        //moreViewsHTML += "<div><a href='"+this.site_url+"/cart_login.php?action="+base64_encode("wishlist")+"&amp;p="+base64_encode(this.product_id)+"&amp;c="+base64_encode(this.category_id)+"'><div class='wishlist'></div>Add to Wish List</a></div>";
		moreViewsHTML+= "<div><form method='post' id='wishListForm' name='wishListForm' action='"+this.secureUrl+"/cart_login.php'><input type='hidden' name='wsh_product_id' value='"+base64_encode(this.product_id)+"' /><input type='hidden' name='wsh_category_id' value='"+base64_encode(this.category_id)+"' /><input type='hidden' name='destination' value='wishlist' /><input type='hidden' name='destination_action' value='addToWishList' /><a href='#' onclick='javascript:moreViews.submitWishListForm(); return false;'><div class='wishlist'></div>Add To Wish List</a></form></div>";
		//Note: 2008 Oct 02
		//moreViewsHTML+="<div id='socialBookmarking'><a href='http://www.addthis.com/bookmark.php' onMouseOver='return addthis_open(this, \"\", \"[URL]\", \"[TITLE]\")' onMouseOut='addthis_close()' onClick='return addthis_sendto()'><img src='../site_files/FiftyFlowers/ff_images/button1-share.gif' width='125' height='16' border='0' alt='' /></a></div>";
		moreViewsHTML+="</div>";
		//Now we palce the HTML contebt inside "moreViews" div.
		this.moreViews.innerHTML = moreViewsHTML;
		
		currentIndex = count;
		var extraImagesLoaded = YAHOO.util.Selector.query('div.imageBox img.elementHidden','leftColumn');
		//var loadingImagesLoaded = YAHOO.util.Selector.query('div.rowImages img.elementVisible','leftColumn');
	
	
		/*
		Note: 2009 Jan 21
		This section was created to add loading gif before the images appear.
		*/
		var loadingImage = "";
		var setImage = "";
		var alt = "";
		var stepDuration = 150;


		for(k=0; k<extraImagesLoaded.length; k++)
		{

			loadingImage = "loading_image_"+currentIndex;
			setImage = "thumbnail_image_"+currentIndex;
			alt = this.alt[currentIndex];
			this.waitForImage(loadingImage, setImage, alt, stepDuration);
			currentIndex++;
			if(currentIndex==this.thumbnail_arr.length)
					currentIndex=0;
		}
		this.placeAsMainImage("0");
		
		
		this.placeAsMainImage("0");
	}

	this.init=function(primary_arr, medium_arr, thumbnail_arr, site_url, product_id, product_url, product_name, category_id)
	{
		//Initialize variables
		this.firstIndex=0;
		this.site_url = site_url;
		this.secureUrl = "https://"+location.hostname;
		this.product_id =  product_id;
		this.product_url = product_url;
		this.product_name = product_name;
        this.category_id = category_id;
		
		this.alt = new Array();
		
		//alert(primary_arr+", "+medium_arr+", "+thumbnail_arr);
		//split by "," each array 
		this.primary_arr=primary_arr.split(",");
		this.medium_arr=medium_arr.split(",");
		this.thumbnail_arr=thumbnail_arr.split(",");
		//eliminate the last element of the array because this is blank
		this.primary_arr.pop();
		this.medium_arr.pop();
		this.thumbnail_arr.pop();
		//get moreViews Div
		this.moreViews = YAHOO.util.Dom.get('moreViews');
		//get mainPictureDiv
		this.mainPicture = YAHOO.util.Dom.get('mainPicture');
		this.showMainPicture = YAHOO.util.Dom.get('showMainPicture');
		/*
		Note: 2009 Jan 27
		Its neccesary to add this class for show correctly the style of the guarantee_fresh box.
		*/
		var guarantee_fresh = YAHOO.util.Dom.get('guarantee_fresh');
		if(guarantee_fresh)
			YAHOO.util.Dom.addClass(guarantee_fresh, 'box_left_first');
		this.placeImages(0);
	}
	
	this.submitWishListForm = function()
	{
		var myForm = document.getElementById("wishListForm");
		if(myForm)
		{
			myForm.submit();
		}
	}

}
/*********************************************************************************************/

var setItemIdBackup=function(p_oEvent)
{
	try{
		YAHOO.util.Dom.get('item_id_backup').value = this.get("checkedButton").get("value");
		//document.getElementById("item_id_backup").value = this.get("value");
		//alert(this.get("checkedButton").get("value"));
	}
	catch(error)
	{
		//alert(""+document.getElementById("item_id_backup").value);	
	}
}

/*
Note: initContainerRight, 2008 jan 31
This function will be triggered when "container_right" is completely loaded.

It makes some initial actions and bind some functions to element events. 
*/
var initContainerRight=function()
{
	/**************** Initializations ***************/
	this.displayBulletOptions = new YAHOO.widget.ButtonGroup("displayBulletOptions");	
	var itemPictureAs=YAHOO.util.Selector.query('div.item div.itemPicture a','container_right');
	var itemPictureTopAs=YAHOO.util.Selector.query('div.item div.itemPictureTop a','container_right');
	var productNames=YAHOO.util.Selector.query('div.item ul li a.productName','container_right');
	var viewAll_links=YAHOO.util.Selector.query('div.item ul li a.viewAll','container_right');
	//To handle the mouse over and mouse out events for "viewAll" links.
	YAHOO.util.Dom.addClass(itemPictureAs, 'itemPictureAOut');
	YAHOO.util.Dom.addClass(itemPictureTopAs, 'itemPictureTopAOut');
	YAHOO.util.Dom.addClass(productNames, 'productNameOut');
	YAHOO.util.Dom.addClass(viewAll_links, 'viewAllOut');
	//alert("length: "+itemPictureAs.length);
	/*************** Delegate events ***************/		
	var items=YAHOO.util.Selector.query('div.item','container_right');
	var l=items.length;
	for(i=0;i<l;i++)
	{
		/*
			Note: addListener, 2008 jan 31
			This method needs 3 parameters: element that will trigger the event, the event name, the function. Moreover,
			you can send an object like an extra parameter to be pass to the function that handles the event.
		*/
		YAHOO.util.Event.addListener(items[i], 'mouseover', item_mouseover, items[i]);
		YAHOO.util.Event.addListener(items[i], 'mouseout', item_mouseout, items[i]);
	}		
	/*************** Delegate events ***************/		
	var items=YAHOO.util.Selector.query('div.item','container_right');
	this.displayBulletOptions.on("click",setItemIdBackup);
}
/*
	Note: item_mouseover, 2008 jan 31
	This function handles the mouseover event for ".item" elements
*/
var item_mouseover=function(e, el)
{
	var itemPictureA=YAHOO.util.Selector.query('div.itemPicture a',el);
	var itemPictureTopA=YAHOO.util.Selector.query('div.itemPictureTop a',el);
	var productName=YAHOO.util.Selector.query('ul li a.productName',el);
	var viewAll=YAHOO.util.Selector.query('ul li a.viewAll',el);
	YAHOO.util.Dom.replaceClass(itemPictureA, 'itemPictureAOut', 'itemPictureAOver');
	YAHOO.util.Dom.replaceClass(itemPictureTopA, 'itemPictureTopAOut', 'itemPictureTopAOver');
	YAHOO.util.Dom.replaceClass(productName, 'productNameOut', 'productNameOver');
	YAHOO.util.Dom.replaceClass(viewAll, 'viewAllOut', 'viewAllOver');
}
/*
	Note: item_mouseover, 2008 jan 31
	This function handles the mouseout event for ".item" elements
*/
var item_mouseout=function(e, el)
{
	var itemPictureA=YAHOO.util.Selector.query('div.itemPicture a',el);
	var itemPictureTopA=YAHOO.util.Selector.query('div.itemPictureTop a',el);
	var productName=YAHOO.util.Selector.query('ul li a.productName',el);
	var viewAll=YAHOO.util.Selector.query('ul li a.viewAll',el);
	YAHOO.util.Dom.replaceClass(itemPictureA, 'itemPictureAOver', 'itemPictureAOut');
	YAHOO.util.Dom.replaceClass(itemPictureTopA, 'itemPictureTopAOver', 'itemPictureTopAOut');		
	YAHOO.util.Dom.replaceClass(productName, 'productNameOver', 'productNameOut');
	YAHOO.util.Dom.replaceClass(viewAll, 'viewAllOver', 'viewAllOut');
}

//Copied on August 4th 2010
function base64_encode (data)
{
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='

    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['atob'] == 'function') {
    //    return atob(data);
    //}
        
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];

    if (!data) {
        return data;
    }

    //data = this.utf8_encode(data+'');
    data = utf8_encode(data+'');
    
    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1<<16 | o2<<8 | o3;

        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);
    
    enc = tmp_arr.join('');
    
    switch (data.length % 3) {
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }

    return enc;
}

function utf8_encode ( argString ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'

    var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    var utftext = "";
    var start, end;
    var stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}
