function swapLayerDisplay(layer) {
	if (document.getElementById(layer).style.display=="none") {
		document.getElementById(layer).style.display="block";	
	}
	else {
		document.getElementById(layer).style.display="none";
	}	
}

function setSearchOption(val) {
	document.getElementById("searchCategoryValue").value=val;
	document.getElementById("trigger").innerHTML=val;
	swapLayerDisplay('searchCategoryOptions');
}


function EnterPressed(e) {
// Code adapted from Jennifer Madden
// http://jennifermadden.com/162/examples/stringEnterKeyDetector.html

  var characterCode
  if(e && e.which){           // NN4 specific code
    e = e
    characterCode = e.which
  }
  else {
    e = event
    characterCode = e.keyCode // IE specific code
  }
  if (characterCode == 13) return true   // Enter key is 13
  else return false
}






// Griz
function showPopups()
{
  //$('.largeWhiteBox').show();
  
  /*$('a#signin').click(function() {
		$('#mainSignIn').toggle(200);
		return false;
	});*/
}

// Griz


function upload(obj)
{
    // Get the name of the file control
   // var id = obj.id.substring(obj.id.lastIndexOf("_")+1);   
    
    // Upload the image to the server folder 
    //var filePath =  obj.value;
    //alert(id);
    // calls the server's method using client callbacks    
   CallServer(obj);// + "?" + filePath);
}

function ReceiveServerData(rValue) 
{
     // The new path will contain the path of the image which is inside the server's folder 
     newPath = rValue;  
     $('#previewImage').attr('src', newPath );
 }
 
 function showSubmit()
 {
    $('#ctl00_Main_btnSubmit').css('visibility','visible');
 }

function OtherTxtBxValHandler(onload)
{
    
    var init = "If your brand is not listed, enter it here";
    var ctrl = $('#ctl00_Main_txtOther');
    
    // If the control exists and it contains a value...
    if (ctrl != null && ctrl.val() != null)
    {
        val = ctrl.val().trim();
        
        if (val == '')
        {
            // We check to see if the the value is blank. If it is, we enable the brands
            // drop down and its associated field validator. We also put the default text into
            // the 'Other' box.
        
            ValidatorEnable( document.getElementById('ctl00_Main_cmbBrandsRequiredFieldValidator'), true);
            $('#ctl00_Main_cmbBrands').attr('disabled', false);
            ctrl.val(init);
        }
        else if (val != init)
        {   
            // If the value isn't blank and isn't equal to the default text we know the user has 
            // entered a different brand. We disable the brands drop down and its associated
            // field validator.
            
            ValidatorEnable( document.getElementById('ctl00_Main_cmbBrandsRequiredFieldValidator'), false);        
            $('#ctl00_Main_cmbBrands').attr('disabled', true);
        }
        else if (onload == false)
            // If neither of the above conditions are met it means that the user has given the box
            // focus. That means we clear the default value and leave the box blank.
            ctrl.val('');

    }
        
}

// Handles displaying character limitations for text fields
//
// textid  - The identifier of the input control to monitor
// limit   - The maximum number of characters allowed
// infodiv - The identifier of the of the div tag where the character count is displayed
function limitChars(textid, limit, infodiv)
{
    var text = $('#' + textid).val(); 
    var textlength = text.length;
    var rval = false;
    
    if(textlength > limit)
    {
        $('#' + infodiv).html('You cannot write more then '+ limit +' characters!');
        $('#' + textid).val(text.substr(0, limit));
    }
    else if(textlength == 0)
        $('#' + infodiv).html(limit + ' Character Limit');
    else
    {
        $('#' + infodiv).html( (limit - textlength) +' / ' + limit);
        rval = true;
    }
    
    return rval;
}

function checkZipFocus(cur, dest)
{
    var length = cur.value.length;
    var MAX = 3;
    
    // If the control is disabled...
    if (!$('#ctl00_Main_' + dest).attr("disabled") == null)
        MAX = 5;
        
    // ...we allow a 5 digit zip code.
    if (length == MAX)
        $('#ctl00_Main_' + dest).focus();

}

// Populates the preview pane with the current form data
//
function populatePreviewPane()
{
    // Get the primary image
    var imgInput = $('#ctl00_Main_hdnPrimaryImage').val();
    
    $('#previewCaption').text( $('#ctl00_Main_txtProdCaption').val() );
    $('#miniPriceTag').html("<sup>$</sup>" + $('#ctl00_Main_txtProdPrice').val() );
    
    // Get Select box values
    $('#categoryData').text( $('#ctl00_Main_cmbCategories :selected').text() );
    $('#genderData').text( $('#ctl00_Main_cmbGenders :selected').text() );
    $('#brandData').text( $('#ctl00_Main_cmbBrands :selected').text() );
    $('#typeData').text( $('#ctl00_Main_cmbTypes :selected').text() );
    $('#sizeData').text( $('#ctl00_Main_cmbSizes :selected').text() );
    
    $('#descriptionData').text( $('#ctl00_Main_txtProdDescr').val() );
}

// Shows a model browser window
function showModel()
{    
    var vimg = document.getElementById("imgid1");
    window.showModalDialog('HTMLPage.htm', vimg.src, "dialogWidth:675px; dialogHeight:625px;center:yes");
}

// Forces a reload of the webpage
function reloadNow(){
    window.location.reload(true);
}

// Saves the posting id to a hidden field
//
// id - The posting Id to save
function savePostingId(id, count)
{
    $('#ctl00_hdnPostingId').val(id);
    $('#ctl00_Main_hdnPostingCount').val(count);
    
    mainSoldDisplayHandler(count);
//    $('#mainSold').toggle(200);
		
//	if( $('#ctl00_Main_hdnSoldVisible').val() == "false")
//	{
//	    $('#ctl00_Main_hdnSoldVisible').val("true");
//	    $('#mainSold').css({ 'top' : 75 + (150 * count) + 'px' });
//	}
//	else
//	{
//	    $('#ctl00_Main_hdnSoldVisible').val("false");
//	    $('#mainSold').css({ 'top' : 75 + (150 * count) + 'px' });
//	}
	    
	return false;
}

function mainSoldDisplayHandler(count)
{
    var ctrlPosY = $('#ctl00_Main_hdnPosY');
    var posY;
        
    if (ctrlPosY != null && ctrlPosY.val() != null)
    {
        posY = ctrlPosY.val();
        
        if (count >= 0)
        {          
            if( $('#ctl00_Main_hdnSoldVisible').val() == "false")
	            $('#ctl00_Main_hdnSoldVisible').val("true");
	        else
    	        $('#ctl00_Main_hdnSoldVisible').val("false");
    	        
    	    $('#mainSold').css({ 'top' : posY + 'px' });
        	    
    	    $('#mainSold').toggle(200);	
        }
        else if($('#ctl00_Main_hdnSoldVisible').val() == "true")
        {
            //ctrlPosY.val(0)
            $('#mainSold').css({ 'top' : posY - 155 + 'px' });
            
            $('#mainSold').toggle(200);	
            
            var currentHref = window.location.href;
            window.location.href = currentHref.substr(0, currentHref.lastIndexOf("#")) + "#item" + $('#ctl00_hdnPostingId').val();

        }
    }
}


function getMouseXY(e) {
    var posX = 0;
    var posY = 0;   
    var oldVal = $('#ctl00_Main_hdnPosY').val();
    var e = (!e) ? window.event : e;   
   
    if (e.pageX || e.pageY) {  
        posX = e.pageX;
        posY = e.pageY;
    }
    else if (e.clientX || e.clientY) {   
        if (document.body.scrollLeft || document.body.scrollTop) {     
            posX = e.clientX + document.body.scrollLeft;    
            posY = e.clientY + document.body.scrollTop;      
        }    
        else {     
            posX = e.clientX + document.documentElement.scrollLeft;     
            posY = e.clientY + document.documentElement.scrollTop;  
        }
    }   
   
    //if (oldVal != null && Math.abs(posY - oldVal) > 30);
        $('#ctl00_Main_hdnPosY').val(posY);
}

function ShowFeaturedItemsText(ctrl)
{
    $('#default').hide();
    $('#product1Info').hide();
    $('#product2Info').hide();
    $('#product3Info').hide();
    $('#product4Info').hide();
    
    ctrl.show();
}

// Initializes the popup (div) event handlers
function initializePopupEvents() {
	$('#contactSellerFooter').hide();
	
	////
	$('#img1').mouseover(function() {
        ShowFeaturedItemsText($('#product1Info'));
        return false;
    });
    
    $('#img2').mouseover(function() {
        ShowFeaturedItemsText($('#product2Info'));
        return false;
    });
    
    $('#img3').mouseover(function() {
        ShowFeaturedItemsText($('#product3Info'));
        return false;
    });
    
    $('#img4').mouseover(function() {
        ShowFeaturedItemsText($('#product4Info'));
        return false;
    });
    ////
	
	$('a#openFlag').click(function() {
		$('#forgotPassword').hide();
		$('#flagInput').toggle(200);
		return false;
	});
	
	$('#previewButton').click(function() {
		$('#previewPane').toggle(200);
		return false;
	});
	
	$('#previewButton1').click(function() {
		$('#previewPane').toggle(200);
		return false;
	});
	
	$('a#signInToFlag').click(function() {
		$('#flagInput').hide();
		$('#flagInputSignIn').toggle(200);
		return false;
	});
	
	$('a#forgotPasswordLink').click(function() {
		$('#flagInputSignIn').hide();
		$('#forgotPassword').toggle(200);
		return false;
	});
	
	$('a#closePassword').click(function() {
		$('#forgotPassword').hide();
		return false;
	});
	
	$('a#closeSold').click(function() {
		$('#mainSold').hide();
		return false;
	});
	
	$('#mainSignIn img').click(function() {
	    return SignInBoxLinkOnClick();
	});
		
	$('a#saveSearch').click(function() {
		$('#saveSearchLayer').toggle(200);
		return false;
	});
	
	$('a#searchboxLabelLink').click(function() {
		$('#everywhere').toggle(200);
		return false;
	});
	
	$('#everywhere img').click(function() {
	    $('#everywhere').toggle(200);
	    return false;
	});
	
	$.fn.wait = function(time, type) {
        time = time || 1000;
        type = type || "fx";
        return this.queue(type, function() {
            var self = this;
            setTimeout(function() {
                $(self).dequeue();
            }, time);
        });
    };
	
	$('#ctl00_btnSearch').click(function() {
		EnableDetailsFormValidation(false);
	});
	
	$('#ctl00_Main_imgBtnSend').click(function() {
		EnableDetailsFormValidation(true);
	});
	
//	$('#ctl00_Main_imgBtnSend').mouseover(function() {
//		EnableDetailsFormValidation(true);
//	});
	
//	$('a#signin').click(function() {   
	
//		$('#mainSignIn').toggle();
//		
//		$('#mainSignIn').focus();
//		$('#ctl00_txtEmail').focus();

//        var cntl = null;
//		if( $('#ctl00_signInVisible').val() == "false")
//		{
//		    $('#ctl00_signInVisible').val("true");
//		    
//		    EnableDetailsFormValidation(false); 
//		}
//		else
//		{
//		    $('#ctl00_signInVisible').val("false");	    
//		    
//		    EnableDetailsFormValidation(true);
//		}
//		alert("here");
//		return SignInBoxLinkOnClick();
//	});
	
	$('a#signin').click(function() {
	    $('#ctl00_createPostSignIn').val("false");
	    return SignInBoxLinkOnClick();
	});
	
	$('a#profileSignin').click(function() {
	    $('#ctl00_createPostSignIn').val("false");
		return SignInBoxLinkOnClick();
	});
	
	$('a#postCreateSignin').click(function() {
	    $('#ctl00_createPostSignIn').val("true");
		return SignInBoxLinkOnClick();
	});
	
	$('a#readyToSellSignin').click(function() {
	    $('#ctl00_createPostSignIn').val("false");
		return SignInBoxLinkOnClick();
	});
	
	
	
	// GRIZ prevents form submittion
	// 
	// $("form").submit(function () { alert("false"); return false; });

}

function SignInBoxLinkOnClick()
{
    $('#mainSignIn').toggle();
		
	$('#mainSignIn').focus();
	$('#ctl00_txtEmail').focus();

    var cntl = null;
	if( $('#ctl00_signInVisible').val() == "false")
	{
	    $('#ctl00_signInVisible').val("true");
	    
	    EnableDetailsFormValidation(false); 
	}
	else
	{
	    $('#ctl00_signInVisible').val("false");	    
	    
	    EnableDetailsFormValidation(true);
	}
	
	return false;
}

function EnableDetailsFormValidation(enable)
{
    cntl = document.getElementById('ctl00_Main_RequiredEmail');
    if (cntl != null)
        ValidatorEnable( cntl, enable);
        
    cntl = document.getElementById('ctl00_Main_txtBuyerNameRequiredFieldValidator');
    if (cntl != null)
        ValidatorEnable( cntl, enable);
        
    cntl = document.getElementById('ctl00_Main_txtBuyerTextRequiredFieldValidator');
    if (cntl != null)
	    ValidatorEnable( cntl, enable); 
}

function callback() {
  //alert("sleep");
  $('#ctl00_txtEmail').focus(); 
}


function loadEventHandelers()
{
    // Function for handling "remaining text" main item description
    $(function(){
        $('#ctl00_Main_txtProdDescr').keyup(function(){
        limitChars('ctl00_Main_txtProdDescr', 500, 'counterInfo');
        })
    });
    
    // Function for handling "remaining text" Flag comment
    $(function(){
        $('#FlagText').keyup(function(){
        limitChars('FlagText', 100, 'counterInfo');
        })
    });
    
    $(function(){
        $('#ctl00_Main_txtProdCaption').keyup(function(){
        limitChars('ctl00_Main_txtProdCaption', 50, 'capCounterInfo');
        })
    });
    
    $(function(){
        $('#ctl00_Main_txtOther').keyup(function(){
        limitChars('ctl00_Main_txtOther', 50, 'otherCounterInfo');
        })
    });
         
    initializePopupEvents();
}

// Toggle the specified checkbox
function toggleCheckbox(prefix, ctlId, itemId)
{
    if ($("#" + prefix + itemId).attr("checked"))
        $("#" + prefix+ itemId).removeAttr("checked");
    else
        $("#" + prefix + itemId).attr("checked","checked");
        
    OnSelectItem(ctlId, itemId);
}

// Griz: Create an AdjancedSearch.js file for all the Advanced Search operations
function toggleAdvancedSearch(ctrl)
{    
    $('#toggleDiv').slideToggle(350);
    if( $('#ctl00_Main_hdnAdvSearchVisible').val() == "false")
    {
	    $('#ctl00_Main_hdnAdvSearchVisible').val("true");
	    ctrl.src = 'Images/common/forms/Hide_BTN.png';
	}
	else
	{
	    $('#ctl00_Main_hdnAdvSearchVisible').val("false");
	    ctrl.src = 'Images/common/forms/View_BTN.png';
	}

    CallServer("hdnAdvSearchVisible:" + $('#ctl00_Main_hdnAdvSearchVisible').val());
}   

function closeAllOpenAdvSrcDropDowns()
{
    $('#locationDrop').hide();
    $('#categoryDrop').hide();
    $('#typeDrop').hide();
    $('#brandDrop').hide();
    $('#sizeDrop').hide();
    $('#genderDrop').hide();
    $('#savedDrop').hide();
    $('#followingDrop').hide();
    $('#provinceDrop').hide();
    $('#cityDrop').hide();
}

function AdvSearchToggleCategory(dropdown)
{
    $(dropdown).toggle(50);
	$('.searchBoxDropDown').hide();
	
	return false;
}

// Creates the handlers for the advanced search menu
//
function createAdvancedSearchHandlers()
{
    // Handle the Search dropdowns
	$('.searchBoxDropDown').hide();
	
	$('a#location').click(function() {
		return AdvSearchToggleCategory('#locationDrop');
	});

    $('div#category').click(function() { 
        return AdvSearchToggleCategory('#categoryDrop');
    });
    
	$('div#type').click(function() {
		return AdvSearchToggleCategory('#typeDrop');
	});
	$('div#brand').click(function() {
		return AdvSearchToggleCategory('#brandDrop');
	});
	$('div#size').click(function() {
		return AdvSearchToggleCategory('#sizeDrop');
	});
	$('div#gender').click(function() {
		return AdvSearchToggleCategory('#genderDrop');
	});
	$('div#saved').click(function() {
		return AdvSearchToggleCategory('#savedDrop');
	});
	$('div#following').click(function() {
		return AdvSearchToggleCategory('#followingDrop');
	});
	
	$('div#province').click(function() {
		return AdvSearchToggleCategory('#provinceDrop');
	});
	$('div#city').click(function() {
		return AdvSearchToggleCategory('#cityDrop');
	});
}

function prepareNavigation() {
			
	//Instantiate the Google Map
	//UNCOMMENT THIS TO USE THE GOOGLE MAPS API
	//initialize();
	
	// Handle the Sign In box
	/*$('#signInBox').hide();
	$('a#signin').click(function() {
		$('#signInBox').toggle(50);
		
		return false;
	});*/
	
	createAdvancedSearchHandlers();
	
	// Function to populate user details
	$('a#populateButton').click(function() {
		$('#buyerName').val($('#yourName').val());
		$('#buyerEmail').val($('#yourEmail').val());
		$('#buyerPhone').val($('#yourPhone').val());
		return false;
	});	
	
	$('a#contactLink').click(function() {
		$('#contactSellerFooter').toggle(250);
		return false;
	});
}