/**
 * Pipit JavaScript Integration 
 * 
 * Requires swfobject 2.1
 *
 * Updated for 7fam by David Knape on 4-25-09
 */

PIPIT = {

  
	CLIENT_URL: "http://www.7forallmankind.com/pipitpurch/",
	CART_URL: "http://www.7forallmankind.com/store/os/shoppingcart.aspx",
	
	cart_id: "",
	chat_window : null,
	connected : false,
	connect_timeout_id: null, 
	
	// start it up
	init: function () {
		
		// first, try pulling cart ID from cookies (7forallmankind.com)  
		var cartId = PIPIT.readCookie( '_store_CartID');
		// no cookie, try pulling from query string
		if(!cartId) cartId = swfobject.getQueryParamValue('cartId');
		// fallback to hard-coded test ID (update as needed during development)
		if(!cartId) cartId = '49b964f5-f025-464c-826c-ae1b3afca786'

		// set the cart ID
		PIPIT.cart_id = cartId;
		
    
    if(document.location.protocol=='file:') {
      PIPIT.CLIENT_URL = 'http://local.7fam/pipitpurch/';
    } else {      
      PIPIT.CLIENT_URL = 'http://'+document.location.host+'/pipitpurch/';
      PIPIT.CART_URL = 'http://'+document.location.host+'/store/os/shoppingcart.aspx';
    }
    
        		
    // check for invite code and update URL
    //PIPIT.checkInvite();
    
    PIPIT.embedLaunchButton();
    
	},
	
	embedLaunchButton: function () {
	   // get product ID from URL
	   var productId = parseInt(swfobject.getQueryParamValue('productid'));
	   if(isNaN(productId)) productId = parseInt( document.location.href.split('/').pop().split('.')[0] );
	   if(isNaN(productId)) productId = 2597; // test id
	   swfobject.embedSWF(PIPIT.CLIENT_URL + "swf/LaunchButton.swf", "pipitLaunchButton", "96", "12", "9.0.28", null, { productId: productId, imageUrl: '/layout/images/createaccount_n.gif' }, { wmode: "transparent" });
	},
	
	launchFromInvite: function () {
    var room = swfobject.getQueryParamValue("room");
    var invite = swfobject.getQueryParamValue("invite");
    PIPIT.launchChatWindow( null, room, invite );
	},
	
	/**
	* Launch the chat window if needed and add a product to the canvas
	*/
	launchChatWindow : function(productId, roomId, invite)
	{
		var client_url = PIPIT.CLIENT_URL;
		var features = "height=768,width=1024,menubar=0,toolbar=0,scrollbars=0,resizable=1,status=1";
		
		var full_url = client_url ;
		var params = {}
		if (productId != null) {
			params['productId'] = productId;
		}	

		if (roomId != null) {
			params['room'] = roomId;
		}	

		if (invite != null) {
			params['invite'] = invite;
		}
		
		// add cart ID to params
		//params['cartId'] = PIPIT.cart_id;
		
		full_url += "#";	
		var sep = "";
		for (var k in params) {
			full_url += sep + k + "=" + params[k];
			sep = "&";
		}
	 	full_url += "&r=" + Math.random(); 		
		
		PIPIT.chat_window = window.open(full_url, "pipit_chat", features);
		
		if (PIPIT.chat_window == null) {
			PIPIT.connected = false;
			alert("You must turn off your popup blocker so you can use Pipit");
			return false;
		}
		
		PIPIT.addToProductPalette( productId );
					
		PIPIT.connected = false;	
		PIPIT.connect_timeout_id = setTimeout(PIPIT.setOwnerWindow, 1000);
		return true;
	},
	
	registerChatWindow : function( chatWin ) 
	{	
	  PIPIT.chat_window = chatWin;
	},
	
	
	/**
	* adds product to product pallete, but only if window is open
	*/
	addToProductPalette : function (productId) 
	{
	  // The "pipit_ready" variable  will be true if it's already opened	
		if (PIPIT.chat_window.pipit_ready == true) {
			PIPIT.chat_window.addToProductPalette(productId);
			PIPIT.chat_window.focus();
			return true;
		} else {
		  return false;
		}
	},
	
	addToProductPalette2 : function (productId) {
	  if(PIPIT.chat_window) {
	    PIPIT.chat_window.addToProductPalette(productId);
	    return 'chat_window found';
	  } else {
	    return 'chat_window not found'
	  }
	//	
	 // The "pipit_ready" variable  will be true if it's already opened	
//		if (PIPIT.chat_window.pipit_ready == true) {
//			PIPIT.chat_window.addToProductPalette(productId);
//			PIPIT.chat_window.focus();
//			alert('adding product id ' + productId);
//	 
//			return true;
//		} else {
//		alert('chat window is not open');
//	 
//		  return false;
//		}

	},
	/**
	* Reload the cart in this parent window
	*/
	refreshCart : function()
	{
		window.location.href = PIPIT.CART_URL;
		window.focus();
	},		
	
	stopConnection : function()
	{
		clearTimeout(PIPIT.connect_timeout_id);
		PIPIT.connect_timeout_id = null;	
	},

	setOwnerWindow : function()
	{
    //console.log( "Chat Window"+ PIPIT.chat_window );
		if (PIPIT.chat_window == null)
		{
			PIPIT.stopConnection();			
			return;
		}

		if (PIPIT.chat_window.pipit_ready)
		{
			PIPIT.connected = true;
			PIPIT.chat_window.setOwner(PIPIT);
			PIPIT.stopConnection();
			return;
		}
		
		PIPIT.connected_timeout_id = setTimeout(PIPIT.setOwnerWindow, 1000);	
	},
	
	

  readCookie : function (name) 
  {
	  var s = name + "="; var ca = document.cookie.split(';');
	  for(var i=0;i < ca.length;i++) {
		  var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length);
		  if (c.indexOf(s) == 0) return c.substring(s.length,c.length);
	  }
	  return null;
  },
  
	parseQuery : function(query_string)
	{
		if (query_string.length == 1)
		{
			return [];
		}

		query_string = query_string.substring(1, query_string.length);
		var query = {};
		var tokens = query_string.split("&");
		
		for (var i = 0; i < tokens.length; i++)
		{
			var kvs = tokens[i].split("=");
			
			query[kvs[0]] = ( kvs.length > 1 ? kvs[1] : null );
		}		

		return query;
	},	

	checkInvite : function()
	{
		var query = this.parseQuery(window.location.search);
		
		if (query.invite == null)
		{
			return;
		}
		
		var location = window.location;
		var new_url = location.protocol + "//" + location.host +  location.pathname + location.hash + "?";

		for (var k in query)
		{
			if (k == "invite" || k == "room")
			{
				continue; // skip invite and room
			}
			new_url += k + "=" + query[k];
		}		
		
		PIPIT.launchChatWindow(null, query.room, query.invite);
	
		window.location = new_url;	
	}
};

PIPIT.init();


