/**************************************************
	File: DakisData.js
	Dakis raw data accessors.

	Javascript Dependencies:

	- DakisAPI.js
***************************************************/





/***************************************************************
	Class: DakisMerchandise
	Import merchandise information into your web page
***************************************************************/
var DakisMerchandise = Class.create();
DakisMerchandise.prototype = {

	// Method: initialize
	initialize: function(productGuid)
	{
		this.productGuid = productGuid;
	},

	// Method: load
	// Load the merchandise information from the server.
	// Binded html element will be updated once the merchandise is loaded.
	load: function()
	{
		this.getMerchandiseInformation();
	},

	// Group: Setters
	// Called while loading the merchandise information.
	// Override these methods to apply your own formatting to
	// the merchandise information attributes

	// Method: setName
	setName: function(name)
	{
		this.name = name;
	},

	// Method: setSpecs
	setSpecs: function(specs)
	{
		var specHtml = "";
		for(var i=0; i<specs.length; i++)
		{
			if( this.isSpecValid(specs[i]) )
			{
				specHtml += "<p>-"+specs[i]+"</p>";
			}
		}

		this.specs = specHtml;
	},

	// Method: setRegPrice
	setRegPrice: function(price)
	{
		this.regPrice = price;
	},

	// Method: setSalePrice
	setSalePrice: function(price)
	{
		this.salePrice = price;
	},
    
    // Method: setSaleText
    setSaleText: function(text)
    {
        this.saleText = text;
    },

	// Method: setImageUrl
	setImageUrl: function(url)
	{
		url = url+"&width="+this.imageWidth+"&height="+this.imageHeight+"&pad=true";
		this.imageUrl = url;
	},

	// Method: setFlag
	setFlag: function(flag)
	{
		this.flag = flag;
	},
    
    // Method: setMAP
    setMAP: function(MAP)
    {
        this.MAP = MAP;
    },


	// Group: Attributes
	// Once loaded, access the merchandise information through the following attributes

	// Variable: productGuid
	productGuid: null,

	// Variable: name
	name: "",

	// Variable: regPrice
	regPrice: "",

	// Variable: salePrice
	salePrice: "",
    
    // Variable: saleText
	saleText: "",

	// Variable: specs
	// Specs come formatted inside <p></p> for each spec
	specs: "",

	// Variable: imageUrl
	imageUrl: "",

	// Variable: flag
	// new, featured, sale, default...
	flag: "",
    
    // Variable: MAP
    // Minimum Advertised Price policy.  If true, can only show item price once in the cart. 
    MAP: false,

	// Group: Data binding
	// Set your html element ids to automatically update their
	// inner html with the corresponding merchandise information.
	// Let empty strings if you don't need some attributes or if you prefer manually handling them.

	// Variable: regPriceBindingId
	// Html element id binded with the regular price.
	regPriceBindingId: "",

	// Variable: salePriceBindingId
	// Html element id binded with the sale price.
	salePriceBindingId: "",

	// Variable: nameBindingId
	// Html element id binded with the name.
	nameBindingId: "",

	// Variable: specsBindingId
	// Html element id binded with the specs.
	specsBindingId: "",

	// Variable: flagBingingId
	// Html element id binded with the flag.
	flagBingingId: "",

	// Variable: imageUrlBindingId
	// Html element id of the image element.  Its src will be set.
	imageUrlBindingId: "",

	// Variable: imageWidth
	// Specify the desired image width.  Set this before loading the merchandise.
	imageWidth: 100,

	// Variable: imageHeight
	// Specify the desired image height.  Set this before loading the merchandise.
	imageHeight: 100,

	// Private section...

	// Called when the merchandise has been filled with information.
	onLoadCompleted: function(dakisMerchandise)
	{
		this.updateHtml();
	},

	// Get the information about a merchandise from the server.
	// Do the AJAX call
	getMerchandiseInformation: function()
	{
		var url = getActionUrl({ action: 'merchandise_information', product_guid: this.productGuid});
		dakisAjaxRequest( url , { asynchronous:true, method:'GET', onComplete: (function(request){this.onMerchandiseInformationCompleted(request.responseText); }).bind(this) }  );
	},

	// once the ajax call is completed, update the attributes...
	onMerchandiseInformationCompleted: function(infoJsonString)
	{
		var info = eval('('+infoJsonString+')');

		this.setName(info.name );
		this.setRegPrice(info.regPrice);
		this.setSalePrice(info.salePrice);
        this.setSaleText(info.saleDisplayText);
		this.setImageUrl(info.imageUrl);
		this.setSpecs(info.specs);
		this.setFlag(info.flag);
        this.setMAP(info.map);

		this.onLoadCompleted(this);
	},

	// Update the html of binded elements with the loaded merchandise information
	updateHtml: function()
	{
		if( $(this.nameBindingId) !== undefined )
		{
			$(this.nameBindingId).innerHTML = this.name;
		}

		if( $(this.specsBindingId) !== undefined )
		{
			$(this.specsBindingId).innerHTML = this.specs;
		}

		if( $(this.regPriceBindingId) !== undefined )
		{
			$(this.regPriceBindingId).innerHTML = this.regPrice;
		}

		if( $(this.salePriceBindingId) !== undefined )
		{
			$(this.salePriceBindingId).innerHTML = this.salePrice;
		}

		if( $(this.imageUrlBindingId) !== undefined )
		{
			$(this.imageUrlBindingId).src = this.imageUrl;
		}

		if( $(this.flagUrlBindingId) !== undefined )
		{
			$(this.flagUrlBindingId).innerHTML = this.flag;
		}
	},

	// indicates wheter this spec can be displayed
	isSpecValid: function(spec)
	{
		if( spec === undefined ||
			spec == "" ||
			spec == "non applicable" ||
			spec == "not applicable" ||
            spec == "unknown" ||
			spec == "&nbsp;")
		{
			return false;
		}

		return true;
	}

};
/**************************************************************
    Class: DakisShowcasedMerchandiseImporter
	Import showcased merchandise sheets into your web page
***************************************************************/
var DakisShowcasedMerchandiseImporter = Class.create();
DakisShowcasedMerchandiseImporter.prototype = {

	/*
		Method: initialize
		Constructor

		Parameters:

		templateHtmlElementId - the element containing the merchandise overview sheet to be filled
								with the merchandise's values. *
		containerHtmlElementId - the element where to insert filled merchandise sheets

		* Tags allowed in the template have the following format: #dakisProductXXX#, where XXX can be:

		- Id
		- Name
		- Specs
		- RegPrice
		- SalePrice
        - SaleText
		- Flag
		- ImageUrl
		- Guid
	*/
	initialize: function(templateHtmlElementId, containerHtmlElementId)
	{
		dakisAssert($(templateHtmlElementId) !== undefined, "DakisShowcasedMerchandiseImporter: templateHtmlElementId is undefined!");
		dakisAssert($(containerHtmlElementId) !== undefined, "DakisShowcasedMerchandiseImporter: containerHtmlElementId is undefined!");

		this.htmlTemplate = $(templateHtmlElementId).innerHTML;
		this.containerId = containerHtmlElementId;
	},

	/*
		Method: start
		Start the merchandise import.  Be sure to have properly set attributes before.
	*/
	start: function()
	{
		var self = this;
		var url = getActionUrl({ action: this.serverAction});
		dakisAjaxRequest( url, {onComplete:
				function(request)
				{
					var merchandises = eval(request.responseText);
					self.importMerchandises(merchandises);                    
				} } );
	},
    
    
    /*
        Method: afterMerchandiseImported
        Called after each merchandise import.
        
        Parameters:
        
        id - the imported merchandise html element id
        merchandise - <DakisMerchandise> object.  Allow to access all data from the merchandise.
        nbMerchandises - total number of merchandises to be imported.  Usefull to set the proper display style.
    */
	afterMerchandiseImported: function(id, merchandise, nbMerchandises)
	{
	},
    
     /*
        Method: afterFinish
        Called once all products have been loaded
    */
    afterFinish: function()
    {    
    },

	// Private section

	importMerchandises: function(merchandises)
	{   
        // for some lazy reason, the array may contains a null element at the end...!
        if( merchandises[merchandises.length-1] == null )
        {
            merchandises.pop();
        }
        
        for(var i=0; i<merchandises.length; i++ )
		{   
            this.createMerchandise(merchandises[i], i, merchandises.length);
		}
        
        this.afterFinish();
	},
    
	createMerchandise: function(merchandiseInfo, id, nbMerchandises)
	{		
        var merchandise = new DakisMerchandise(merchandiseInfo.guid);
        merchandise.setName(merchandiseInfo.name);
        merchandise.setSpecs(merchandiseInfo.specs);
        merchandise.setRegPrice(merchandiseInfo.regPrice);
        merchandise.setSalePrice(merchandiseInfo.salePrice);
        merchandise.setSaleText(merchandiseInfo.saleDisplayText);
        merchandise.imageWidth = this.imageWidth;
		merchandise.imageHeight = this.imageHeight;
        merchandise.setImageUrl(merchandiseInfo.imageUrl);
        merchandise.setFlag(merchandiseInfo.flag);
        merchandise.setMAP(merchandiseInfo.map);		        
		
		this.importMerchandise(merchandise, merchandiseInfo.guid, id, nbMerchandises);
	},

	importMerchandise: function(merchandise, guid, id, nbMerchandises)
	{
		
        var html = this.htmlTemplate;

		var idStr = this.containerId+"DakisProduct"+id;
		html = this.replaceTag(html, "Id", idStr);
		html = this.replaceTag(html, "Name", merchandise.name);

		html = this.replaceTag(html, "Specs", merchandise.specs);
		html = this.replaceTag(html, "RegPrice", merchandise.regPrice);
		html = this.replaceTag(html, "SalePrice", merchandise.salePrice);
        html = this.replaceTag(html, "SaleText", merchandise.saleText);
		html = this.replaceTag(html, "ImageUrl", merchandise.imageUrl);
		html = this.replaceTag(html, "Guid", guid);

		var flag = merchandise.flag;
		if( flag == "default" )
		{
			flag = "featured";
		}
		html = this.replaceTag(html, "Flag", flag);

		var element = document.createElement("div");
		element.innerHTML = html;

		$(this.containerId).appendChild(element);        

		this.afterMerchandiseImported(idStr, merchandise, nbMerchandises);
	},

	replaceTag: function(text, tag, value)
	{
		return stringReplace(text, "#dakisProduct"+tag+"#", value);
	},

	// Group: Attributes

	// Variable: imageWidth
	// Desired image width in pixels
	imageWidth: 100,

	// Variable: imageHeight
	// Desired image height in pixels
	imageHeight: 100,
    
    // Variable: serverAction
    // Action to call to retrieve products.  By default, get the showcased products.  
    serverAction: "showcased_products",

	containerId: null,
	htmlTemplate: ""
};

/***************************************************************
	Class: DakisCartIndicatorInformation
	Import cart indicator information (number of items, subtotal...)
***************************************************************/
var DakisCartIndicatorInformation = Class.create();
DakisCartIndicatorInformation.prototype = {

    initialize: function()
	{
	},


	// Method: load
	// Load the cart indicator information from the server.
	// Binded html element will be updated once the merchandise is loaded.
	load: function()
	{
		this.getCartIndicatorInformation();
	},

	// Group: Setters
	// Called while loading the cart indicator information.
	// Override these methods to apply your own formatting to
	// the cart indicator information attributes

	// Method: setNbItems
	setNbItems: function(nbItems)
	{
		this.nbItems = nbItems;
	},

	// Method: setSubtotal
	setSubtotal: function(subtotal)
	{
		this.subtotal = subtotal;
	},

	// Method: setNbItemText
	setNbItemText: function(text)
	{
		this.nbItemText = text;
	},	
	
	// Private section...

	// Called when the cart indicator has been filled with information.
	onLoadCompleted: function()
	{
		this.updateHtml();
	},

	// Get the cart indicator information
	// Do the AJAX call
	getCartIndicatorInformation: function()
	{
		var url = getActionUrl({ controller: 'cart', action: 'cart_indicator_information', lang: g_dakisLang});
		dakisAjaxRequest( url , { asynchronous:true, method:'GET', onComplete: (function(request){this.onCartIndicatorInformationCompleted(request.responseText); }).bind(this) }  );
	},

	// once the ajax call is completed, update the attributes...
	onCartIndicatorInformationCompleted: function(infoJsonString)
	{		
        var info = eval('('+infoJsonString+')');
        
		this.setNbItems(info.nbItems );
		this.setSubtotal(info.subtotal);        
		this.setNbItemText(info.nbItemText);		
		this.onLoadCompleted();
	},

	// Update the html of binded elements with the loaded merchandise information
	updateHtml: function()
	{
        if( $(this.nbItemsBindingId) !== undefined )
		{
			$(this.nbItemsBindingId).innerHTML = this.nbItems;
		}

		if( $(this.subtotalBindingId) !== undefined )
		{
			$(this.subtotalBindingId).innerHTML = this.subtotal;
		}

		if( $(this.nbItemTextBindingId) !== undefined )
		{
			$(this.nbItemTextBindingId).innerHTML = this.nbItemText;
		}		
	},
    
    // Group: Attributes
	// Once loaded, access the cart indicator information through the following attributes

	// Variable: nbItems
	nbItems: null,

	// Variable: subtotal
	subtotal: "",

	// Variable: setNbItemText
	nbItemText: "",

	// Group: Data binding
	// Set your html element ids to automatically update their
	// inner html with the corresponding cart indicator information.
	// Let empty strings if you don't need some attributes or if you prefer manually handling them.

	// Variable: nbItemsBindingId
	// Html element id binded with the number of items.
	nbItemsBindingId: "",

	// Variable: subtotalBindingId
	// Html element id binded with the subtotal.
	subtotalBindingId: "",

	// Variable: setNbItemTextBindingId
	// Html element id binded with the number of item label.
	nbItemTextBindingId: ""
};

