/*
	Opens a new window with the provided url and dimension
	
	@param url the url to open	
	@param width the window width
	@param height the window height
*/

  function getPageSize()
  {
  	var xScroll, yScroll;

  	if (window.innerHeight && window.scrollMaxY) {	
  		xScroll = document.body.scrollWidth;
  		yScroll = window.innerHeight + window.scrollMaxY;
  	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
  		xScroll = document.body.scrollWidth;
  		yScroll = document.body.scrollHeight;
  	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
  		xScroll = document.body.offsetWidth;
  		yScroll = document.body.offsetHeight;
  	}

  	var windowWidth, windowHeight;

  	if (self.innerHeight) {	// all except Explorer
  		windowWidth = self.innerWidth;
  		windowHeight = self.innerHeight;
  	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
  		windowWidth = document.documentElement.clientWidth;
  		windowHeight = document.documentElement.clientHeight;
  	} else if (document.body) { // other Explorers
  		windowWidth = document.body.clientWidth;
  		windowHeight = document.body.clientHeight;
  	}	
  	var pageHeight, pageWidth;

  	// for small pages with total height less then height of the viewport
  	if(yScroll < windowHeight){
  		pageHeight = windowHeight;
  	} else { 
  		pageHeight = yScroll;
  	}

  	// for small pages with total width less then width of the viewport
  	if(xScroll < windowWidth){	
  		pageWidth = windowWidth;
  	} else {
  		pageWidth = xScroll;
  	}

  	return {pageWidth: pageWidth ,pageHeight: pageHeight , windowWidth: windowWidth, windowHeight: windowHeight};
  }
  
function openPopup( url, width, height )
{
	if (url != null)
	{
		if (width != null && height != null)
		{	
			window.open(url, "", "width=" + width +", height=" + height +", scrollbars=no, resizable=yes");
		}
		else
		{
			window.open(url, "", "scrollbars=no, resizable=yes");
		}		
	}
}

function openProductCompareWindow( url )
{
	window.open(
		url,
		'product_compare',
		'width=800,height=600,scrollbars=yes,resizable=yes',
		true /* replace history in the popped up window */
	).focus();
}

function showCSSPopup(popupId)
{
	if(!Element.visible(popupId))
	{
		center(popupId);
	   	Effect.Appear(popupId);
   	}
}

// instanciate XMLRequester
xmlHttp = Ajax.getTransport(); //getXMLRequester();

// constants
var REQUEST_GET        = 0;
var REQUEST_POST        = 2;
var REQUEST_HEAD    = 1;
var REQUEST_XML        = 3;

/**
 * sends a http request to server
 *
 * @param strSource, String, datasource on server, e.g. data.php
 *
 * @param strData, String, data to send to server, optionally
 *
 * @param intType, Integer,request type, possible values: REQUEST_GET, REQUEST_POST, REQUEST_XML, REQUEST_HEAD default REQUEST_GET
 *
 * @param intID, Integer, ID of this request, will be given to registered event handler onreadystatechange', optionally
 *
 * @param resultHandler, Function, the function to be invoked to process the result (takes two arguments 'xmlHttp' and 'intID'), optionally
 *
 * @return String, request data or data source
 */
function sendRequest( strSource, strData, intType, intID, resultHandler )
{
    if( !strData )
        strData = '';

    // default type (0 = GET, 1 = xml, 2 = POST )
    if( isNaN( intType ) )
        intType = 0; // GET

    // previous request not finished yet, abort it before sending a new request
    if( xmlHttp && xmlHttp.readyState )
    {
        xmlHttp.abort( );
        xmlHttp = false;
    }
        
    // create a new instance of xmlhttprequest object
    // if it fails, return
    if( !xmlHttp )
    {
        xmlHttp = Ajax.getTransport(); //getXMLRequester( );
        if( !xmlHttp )
            return;
    }
    
    // parse query string
    if( intType != 1 && ( strData && strData.substr( 0, 1 ) == '&' || strData.substr( 0, 1 ) == '?' ) )
        strData = strData.substring( 1, strData.length );

    // data to send using POST
    var dataReturn = strData ? strData : strSource;
    
    switch( intType )
    {
        case 1:    // xml
            strData = "xml=" + strData;
        case 2: // POST
            // open the connection 
            xmlHttp.open( "POST", strSource, true );
            xmlHttp.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
            xmlHttp.setRequestHeader( 'Content-length', strData.length );
            xmlHttp.setRequestHeader( 'Accept', 'text/javascript, text/html, application/xml, text/xml, */*' );
            break;
        case 3: // HEAD
            // open the connection 
            xmlHttp.open( "HEAD", strSource, true );
            strData = null;
            break;
        default: // GET
            // open the connection 
            var strDataFile = strSource + (strData ? '?' + strData : '' );
            xmlHttp.open( "GET", strDataFile, true );
            strData = null;
    }
    
    // set onload data event-handler
    xmlHttp.onreadystatechange = new Function( "", "processResponse(" + intID + "," + resultHandler + ")" );

    // send request to server
    xmlHttp.send( strData );    // param = POST data

    return dataReturn;
}

/**
 * process the response data from server
 *
 * @param intID, Integer, ID of this response
 */
function processResponse( intID, resultHandler )
{
    // status 0 UNINITIALIZED open() has not been called yet.
    // status 1 LOADING send() has not been called yet.
    // status 2 LOADED send() has been called, headers and status are available.
    // status 3 INTERACTIVE Downloading, responseText holds the partial data.
    // status 4 COMPLETED Finished with all operations.
    switch( xmlHttp.readyState )
    {
        // uninitialized
        case 0:
        // loading
        case 1:
        // loaded
        case 2:
        // interactive
        case 3:
            break;
        // complete
        case 4:    
            // check http status
            if( xmlHttp && xmlHttp.status && xmlHttp.status == 200 )    // success
            {
                if(resultHandler != null){
                	resultHandler( xmlHttp, intID )
                }else{
                	processData( xmlHttp, intID );
                }
            }
            // loading not successfull, e.g. page not available
            else
            {
                //if( window.handleAJAXError )
                //    handleAJAXError( xmlHttp, intID );
                //else
                //    alert( "ERROR\n HTTP status = " + xmlHttp.status + "\n" + xmlHttp.statusText ) ;
            }
    }
}


// process data from server
function insertCartPopup( xmlHttp, intID )
{
    $('carthtml').innerHTML = xmlHttp.responseText;
	if (null == $('inventorypopup')) {
		if ($('cartitemsbag') && $('cartitemsbag').innerHTML != '0 items') {
			$('cartitemshead').innerHTML = $('cartitemsbag').innerHTML;
		}
	}
    //Rico.Corner.round(".bagtitle", {blend: true, border: "#CC0001", corners: "top"});
	//Rico.Corner.round(".bagmain", {blend: true, border: "#CC0001", corners: "bottom"});
	//not gonna use rico on barneys, cause it is...not good.

	// dirty, dirty hack for older IE versions
	if ((navigator.appName == "Microsoft Internet Explorer") &&
		(navigator.appVersion.indexOf("MSIE 6.0") != -1 ||
		 navigator.appVersion.indexOf("MSIE 5.5") != -1 ||
		 navigator.appVersion.indexOf("MSIE 5.0") != -1)){
		var cartpopup = $('cartpopup');
		//cartpopup.style.position = 'absolute';
		//cartpopup.style.top = '102';
		//cartpopup.style.bottom = '';
		iframeHack('cartpopup');
	}
    if(!Element.visible('cartpopup'))
	    Effect.SlideDown('cartpopup');
}

// 
function insertWishlistPopup( xmlHttp, intID )
{
    $('wishlisthtml').innerHTML = xmlHttp.responseText;
    if(!Element.visible('wishlistpopup'))
    {
	    center('wishlistpopup');
	    Effect.Appear('wishlistpopup');
	}
}

function insertVariationSnippet( xmlHttp, intID )
{
    $('variationsnippet').innerHTML = xmlHttp.responseText;
}


// handle response errors
function handleAJAXError( xmlHttp, intID )
{
	alert('An error occured.\nHTTP Status code:'+xmlHttp.status);
}

function addToCart( button, resultHandler ) {
	var form = button.form;
	button.disabled = true;
	var url = form.action;
	var querystring = '';
	for (i = 0; i < form.elements.length; ++i){
		if( (form.elements[i].type == "checkbox")) {
			querystring += form.elements[i].name + '=';
			querystring += form.elements[i].checked ? "true" : "false";
			querystring += "&";
		}else if( !(form.elements[i].type == "submit")) {
			querystring += form.elements[i].name + '=' + escape(form.elements[i].value) + "&";
		}
	}
	querystring += button.name+'='+escape(button.value)+'&Popup=true';
	url += "?"+querystring;
	new Ajax.Request( url, {
		method: 'get',
		onSuccess: function(transport) {
			$('carthtml').innerHTML = transport.responseText;
			if (null == $('inventorypopup')) {
				if ($('cartitemsbag') && $('cartitemsbag').innerHTML != '0 items') {
					$('cartitemshead').innerHTML = $('cartitemsbag').innerHTML;
				}
			}
			if( !Element.visible('cartpopup') ) {
	    		Effect.SlideDown('cartpopup');
	    	}
	    	button.disabled = false;
		},
		onFailure: function() {
			alert( "Error at adding a product to the cart" );
			button.disabled = false; 
		}
	});

	return false;
}

function postDHTML( button, resultHandler ){
	querystring = '';
	var form = button.form;
	//button.disabled = true;
	for (i = 0; i < form.elements.length; ++i){
		if((form.elements[i].type == "checkbox"))
		{
			querystring += form.elements[i].name + '=';
			querystring += form.elements[i].checked ? "true" : "false";
			querystring += "&";
		}else if(!(form.elements[i].type == "submit")){
			querystring += form.elements[i].name + '=' + escape(form.elements[i].value) + "&";
		}
	}
	querystring+=button.name+'='+escape(button.value)+'&Popup=true';
	//alert(form.action+'?'+querystring);
	sendRequest(form.action,querystring,REQUEST_GET,4,resultHandler);
	return false;
}

function getDHTML( url, querystring, resultHandler, intID )
{
	if (intID == undefined)
	{
		intID = 4;
	}
	if (querystring == null || querystring == ''){
		querystring='Popup=true';
	}else{
		querystring+='&Popup=true';
	}
	sendRequest(url,querystring,REQUEST_GET,intID,resultHandler);
	return false;
}

function center(e)
{
    var w = (Element.getDimensions('container').width / 2) - (Element.getDimensions(e).width / 2);
    var h = (getPageSize().windowHeight / 2) - (Element.getDimensions(e).height / 2);
    xMoveTo($(e), w, 90);
}

var timer=null;
var scClose=null;
function doCartPopup(_v, url)
{
  if(_v)
  {
  	if(!Element.visible('cartpopup'))
  	{
    	timer=window.setTimeout('cartPopupAction("'+url+'")',300); //0.3 seconds
    }
    if(scClose)
    {
	  window.clearTimeout(scClose);
	  scClose=null;
    }
  }
  else
  {
    if(timer)
	{
	  window.clearTimeout(timer);
	  timer=null;
	}
  	if(Element.visible('cartpopup'))
	{
	  scClose=window.setTimeout('closeCartPopup()',2000); //2 seconds
	}
  }
}

function closeCartPopup()
{
	window.clearTimeout(scClose);
	sclose = null;
	if(Element.visible('cartpopup'))
	{
		Effect.SlideUp('cartpopup');
	}
}

function cartPopupAction(url)
{
	if(!Element.visible('cartpopup'))
	{
		getDHTML(url,'','insertCartPopup');
	}
}

// ie layer hack to make sure no select boxes or inputs appear through the minicart dropdown

function iframeHack(element){
	element = $(element);
	var index = element.childNodes.length - 1;
	var lastNode = element.childNodes[index];
	if(lastNode != null && lastNode.className != "iframehack"){
		var iframe = document.createElement("iframe");
		iframe.src = "javascript:'';";
		iframe.frameBorder="0";
		iframe.scrolling="no";
		iframe.style.position="absolute";
		iframe.style.left="0px";
		iframe.style.top="0px";
		iframe.style.overflow = "hidden";
		iframe.className = "iframehack";
		iframe.ID = "cartpopupiFrame";
		var elementDimensions = Element.getDimensions(element);
		iframe.style.width = elementDimensions.width;
		iframe.style.height = elementDimensions.height;
		iframe.style.zIndex = new Number(element.style.zIndex) - 1;
		element.appendChild(iframe);
	}
}

// flash stuff (IE security workaround)
function insertFlash(url, width, height){
	document.write('<object codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" id="ProductFlash" type="application/x-shockwave-flash" width="'+width+'" height="'+height+'" data="'+url+'">');
	document.write('	<param name=movie value="'+url+'">');
	document.write('	<param name="wmode" value="transparent">');
    document.write('    <EMBED src="'+url+'" WIDTH="'+width+'" HEIGHT="'+height+'" SWLIVECONNECT="true" NAME="ProductFlash"');
	document.write('        TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">');
    document.write('    </EMBED>');
	document.write('</object>');
}

// functions for ShopByCatalog resolve masters
function insertResolveVariationSnippet( xmlHttp, intID )
{
    $('variationinfo'+intID).innerHTML = xmlHttp.responseText;
}
