if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}

var category_to_display = 0;
var product_to_display  = 0;
var loading_uris        = [];
var current_mouse_over = 0;

$( document ).ready( function()
{
	$( '#ajax_cache' ).hide();
	
	$( '#left .box h2' ).after( $( '#filters' ) );
	
	if( $( '#filters' ) )
	{
		//$( '#left .box #filters' ).after( 'test' );
	}
	
	$( '#header' ).append( $( '.top_crumbs' ) );

	$( '#header' ).append( $( '.browse_category' ) );
	
	$( '#header' ).append( $( '.category_description' ) );
	
	$( "#nav td" ).mouseover( function() {
		$( this ).addClass( 'hover' );
	} );
	$( "#nav td" ).mouseout( function() {
		$( this ).removeClass( 'hover' );
	} );
	
	$( "#main_categories > li" ).mouseover( function( evt ) {
		var e=(evt)?evt:window.event;
	    if (window.event) {
	        e.cancelBubble=true;
	    } else {
	    	e.cancelBubble = true;
	        e.stopPropagation();
	    }
		$( "#main_categories > li.whatshot" ).removeClass( 'hover' );
		$( this ).addClass( 'hover' );
	} );
	$( "#main_categories > li" ).mouseout( function( evt ) {
		var e=(evt)?evt:window.event;
	    if (window.event) {
	        e.cancelBubble=true;
	    } else {
	    	e.cancelBubble = true;
	        e.stopPropagation();
	    }
		$( this ).removeClass( 'hover' );
	} );
	
	$( "#main_categories" ).mouseout( function( evt ) {
		var e=(evt)?evt:window.event;
	    if (window.event) {
	        e.cancelBubble=true;
	    } else {
	    	e.cancelBubble = true;
	        e.stopPropagation();
	    }
		$( '#main_categories > li.whatshot' ).addClass( 'hover' );
	});
	
	var i = 0;
	$( '#nav td a' ).each( function() {
		var rel = $( this ).attr( 'rel' );
		if( rel && rel == selected_microsite )
		{
			if( selected_microsite == 'home' )
			{
				$( this ).parent().parent().addClass( 'active' );
			}
			else
			{
				$( this ).parent().addClass( 'active' );
			}
			if( i )
			{
				$( '#nav td:eq(' + ( i - 1 )  + ')' ).addClass( 'previous' );
			}
		}
		if( rel == 'home' )
		{
			i++
		}
		else
		{
			if( $( this ).parent().get( 0 ).tagName == 'TD' )
			{
				i++;
			}
		}
	} );
	
	$( '#hot_categories .ajax_quick .main_photo' ).before( $( '#main_photo' ) );
	
	$( '.shop_by_brand table tr td.brands' ).each( function() {
		
		var box_type = $( this ).attr( 'rel' );
		switch( box_type )
		{
			case 'left_type':
				randomBrands( 3, $( this ), box_type );
				break;
			case 'right_type':
				randomBrands( 6, $( this ), box_type );
				break;
			case 'center_type':
				randomBrands( 5, $( this ), box_type );
				break;
		}
		
	} );
	$( '.shop_by_brand td.left' ).click( function()
	{
		var parent = $( this ).parent().parent();
		var box_type = $( 'td.brands', parent ).attr( 'rel' );
		var how_many = 5;
		switch( box_type )
		{
			case 'left_type':
				how_many = 3;
				break;
			case 'right_type':
				how_many = 6;
				break;
			case 'center_type':
				how_many = 5;
				break;
		}
		randomBrands( how_many, $( 'td.brands', parent ), $( 'td.brands', parent ).attr( 'rel' ) );
	} );
	$( '.shop_by_brand td.right' ).click( function()
	{
		var parent = $( this ).parent().parent();
		var box_type = $( 'td.brands', parent ).attr( 'rel' );
		var how_many = 5;
		switch( box_type )
		{
			case 'left_type':
				how_many = 3;
				break;
			case 'right_type':
				how_many = 6;
				break;
			case 'center_type':
				how_many = 5;
				break;
		}
		randomBrands( how_many, $( 'td.brands', parent ), $( 'td.brands', parent ).attr( 'rel' ) );
	} );
	
	$( '.footer_newsletter #subscriber_name' ).focus( function() {
		if( $( this ).val() == 'first name'  )
		{
			$( this ).val( '' );
		}
	} );
	$( '.footer_newsletter #subscriber_name' ).blur( function() {
		if( $( this ).val() == '' )
		{
			$( this ).val( 'first name' );
		}
	} );
	$( '.footer_newsletter #subscriber_email' ).focus( function() {
		if( $( this ).val() == 'your email address'  )
		{
			$( this ).val( '' );
		}
	} );
	$( '.footer_newsletter #subscriber_email' ).blur( function() {
		if( $( this ).val() == '' )
		{
			$( this ).val( 'your email address' );
		}
	} );
	
	$("#inputString").autocomplete("/search/suggestion", { minChars:2 });
	
	/* AJX */
	
	$( '#hot_categories .mainajx' ).bind( 'mouseover', function( e )
	{
		if( ! e.target )
		{
			return;
		}
		
		var el = $( e.target );	
		
		if( el.is( 'span' ) &&
		    el.parent().is( '.mainajx' ) )
		{
			el = el.parent();
		}
		if( el.is( 'img' ) &&
	    el.parent().parent().is( '.mainajx' ) )
	    {
	    	el = el.parent().parent();
	    }
		if( el.is( '.mainajx' ) )
		{
			if( category_to_display == el.attr( 'rel' ) )
			{
				return;
			}
			
			category_to_display = el.attr( 'rel' );
			displayCategory( '/topfive/params/category/' + escape( el.attr( 'rel' ) ), escape( el.attr( 'rel' ) ) );
			return;
		}
		
		if( el.is( 'span' ) &&
		    el.parent().is( '.secajx' ) )
		{
			el = el.parent();
		}
		if( el.is( 'img' ) &&
	    el.parent().is( '.secajx' ) )
	    {
	    	el = el.parent();
	    }
		if( el.is( '.secajx' ) )
		{
			if( product_to_display == el.attr( 'rel' ) )
			{
				return;
			}
			
			product_to_display = el.attr( 'rel' );
			displayProduct( '/product/quick/params/id/' + escape( product_to_display ), escape( product_to_display ) );
			return;
		}
	} );
	
	if( $( '#mainSearch' ) ) 
	{
		$( '#mainSearch' ).focus();
	}
	
	if( ! $.browser.msie )
	{
		$( '#nav td.items' ).each( function() {
			var left = $( this ).get(0).offsetLeft;
			$( 'ul', this ).css( "left", left + "px" );
		} );
	}
	
	$( '#top_nav .feedback' ).click( function() {
		window.open( "/message/suggestion", "", "width=970,height=250,scrollbars=yes" );
		return false;
	} );
	
	$( '#top_nav .tell_friend' ).click( function() {
		window.open( "/message/friend", "", "width=970,height=250,scrollbars=yes" );
		return false;
	} );
	$( '.compare_checkbox_button' ).click( function() {
		var compare_string = '';
		var how_many = 0;
		$( '.compare_checkbox' ).each( function() {
			var product_checked = $( this ).attr( 'checked' );
			var product_value = $( this ).attr( 'value' );
			if( product_checked == true )
			{
				if( compare_string != '' )
				{
					compare_string = compare_string + '-' + product_value;
				}
				else
				{
					compare_string = product_value
				}
				how_many++;
			}
		} );
		if( how_many < 2 )
		{
			return alert( 'Please select at least 2 products.' );
		}
		if( compare_string != '' )
		{
			return redirectTO( '/compare.php?compare=' + compare_string );
		}
		return false;
	} );

	formAjaxSubmit();
	
});

function formAjaxSubmit()
{
	var form_submit_options = { 
        target:        '#suggestion_box_div',   // target element(s) to be updated with server response 
        beforeSubmit:  showRequest,  // pre-submit callback 
        success:       showResponse  // post-submit callback 
 
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    }; 
 
    // bind form using 'ajaxForm' 
    $('#suggestion_box').ajaxForm(form_submit_options);
}

// pre-submit callback 
function showRequest(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    var queryString = $.param(formData); 
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 
 
   // alert('About to submit: \n\n' + queryString); 
 $( '#loading_form_ajax' ).show();
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 
    return true; 
} 
 
// post-submit callback 
function showResponse(responseText, statusText)  { 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 
 
   // alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
     //   '\n\nThe output div should have already been updated with the responseText.'); 
     $( '#loading_form_ajax' ).hide();
    formAjaxSubmit();
}

function redirectTO( url )
{
	document.location=url;
}

function randomBrands( how_many, target, type )
{
	$.get( '/brands/random/params/total/' + how_many + '/type/' + type, function( abc ) { $( 'div', target ).hide().html( abc ).fadeIn() } );
}

function removeSomeClass()
{
	$( '.secajx' ).removeClass( 'active' );
}

/* --- */

function displayWhenReady( id, type )
{
	if( type == 'category' )
	{
		if( ( category_to_display > 0 ) &&
			( category_to_display != id ) )
		{
			return;
		}
		
		var elem = '.ajax_quick';
	}
	else
	{
		if( ( product_to_display > 0 ) &&
			( product_to_display != id ) )
		{
			return;
		}
		
		var elem = '.ajax_quick .quick_product';
	}
	
	$( elem ).html( '' );
	
	$( '#ajx' + id ).clone().appendTo( elem );
	
	if( type == 'category' )
	{
		var firstprod = $( '#ajx' + id + ' a.secajx:first' );
		if( firstprod.length )
		{
			product_to_display = firstprod.attr( 'rel' );
			var category_name = firstprod.attr( 'name' );
			displayProduct( '/product/quick/params/id/' + escape( product_to_display ) + '?c=' + escape( category_name), escape( product_to_display ) );
		}
	}
}

function displayCategory( uri, id )
{
	
	$( '.ajax_quick' ).html( '' );
	
	if( loading_uris.indexOf( id ) > -1 )
	{
		return;
	}

	if( $( '#ajx' + id ).length )
	{
		displayWhenReady( id, 'category' );
		refreshBind();
	}
	else
	{
		loading_uris.push( id );

		$.get( uri, function( html )
		{
			loading_uris.splice( loading_uris.indexOf( id ), 1 );
			
			$( '#ajax_cache' ).append( '<div id="ajx' + id + '" class="something">' + html + '</div>' );
			displayWhenReady( id, 'category' );
			refreshBind();
		} );
	}
}

function displayProduct( uri, id )
{
	$( '.ajax_quick .quick_product' ).html( '' );
	
	if( loading_uris.indexOf( id ) > -1 )
	{
		return;
	}

	if( $( '#ajx' + id ).length )
	{
		displayWhenReady( id, 'product' );
	}
	else
	{
		loading_uris.push( id );
		
		$.get( uri, function( html )
		{
			loading_uris.splice( loading_uris.indexOf( id ), 1 );
			
			$( '#ajax_cache' ).append( '<div id="ajx' + id + '" class="something">' + html + '</div>' );
			displayWhenReady( id, 'product' );
		} );
	}
}

function refreshBind()
{
	$( '#hot_categories .secajx' ).bind( 'mouseover', function( e )
	{
		if( ! e.target )
		{
			return;
		}
		
		var el = $( e.target );	
		
		if( el.is( 'span' ) &&
		    el.parent().is( '.secajx' ) )
		{
			el = el.parent();
		}
		if( el.is( 'img' ) &&
	    el.parent().is( '.secajx' ) )
	    {
	    	el = el.parent();
	    }
		if( el.is( '.secajx' ) )
		{
			removeSomeClass();
			$( el ).addClass( 'active' );
			if( product_to_display == el.attr( 'rel' ) )
			{
				return;
			}
			var category_name = el.attr( 'name' );
			product_to_display = el.attr( 'rel' );
			displayProduct( '/product/quick/params/id/' + escape( product_to_display ) + '?c=' + escape( category_name ), escape( product_to_display ) );
			return;
		}
	} );	
}

function bookmark(url,title){
  if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
  window.external.AddFavorite(url,title);
  } else if (navigator.appName == "Netscape") {
    window.sidebar.addPanel(title,url,"");
  } else {
    alert("Press CTRL-D (Netscape) or CTRL-T (Opera) to bookmark");
  }
}
