/************************************** Splendid **************************************
* Created By: Steve Doggett
* Created On: 9th September
*
* Edited ----------------------------------------------------------------------------
*		By:				On:
* Description -----------------------------------------------------------------------
*		Various page control functions
* 		
* Functions -------------------------------------------------------------------------
*       toggleDiv()             // Function to hide/show a specified div element
*       populateElement()       // Function to put some default text into an input box. 
*       divToggle()             // Another function to hide/show a div element
*       openBrowser()           // Open a new browser window
*       closePanel()            // Toggles a panel (div) up or down
*       changeToEdit()          // Changes a chunk of text into an editable input box
*       addNewTag()             // Function to add the newly input tag to the tags list on object_viewObject_AddItem_Description.html
*       removeTag()             // Function to remove a tag from the list on object_viewObject_AddItem_Description.html
*       updateCharity()         // Function to add new options to a drop down on object_viewObject_AddItem_Price.html
*       updateDropDown()        // Function to add new options to a drop down on object_viewObject_AddItem_Price.html
*       enableFinish()          // Function to check all boxes are ticked on the terms page object_viewObject_AddItem_Terms.html
*       checkLocationlabel()    // Checks if new selected from the drop down and show the new label box.
*       openMapPopup()          // Opens the map popup to display an item on the map.
************************************************************************************/

// Anything in here will be triggered when the page is ready (so all DIV's are present etc.)

/*$(document).ready(function(){
    populateElement('#items', 'find all items to borrow ..');
    populateElement('#wanted', 'search wanted ads ..');	
	populateElement('#location', 'any location');
	populateElement('#people', 'find people by name or e-mail address ..');
	populateElement('#anylocation', 'any location');
	populateElement('#postCode', 'enter your location here ..');
	populateElement('#circles', 'find all circles...');
	populateElement('#charity', 'enter a keyword...');
	populateElement('#use','please describe here what your intended use of this item will be...');
	populateElement('#message','please add an optional message.. for example when you could collect the item...');
	populateElement('#cause','enter your new good cause here...');
	populateElement('#newcircle','please enter the name of your circle ..');
	populateElement('#title','please enter the title of your item ..');
	populateElement('#andwhy','please state your intended use...');
	populateElement('#circlelocation','enter the location of your circle');	
	populateElement('#where','where?');
	populateElement('#near','any location');
	populateElement('#label','enter label');
	populateElement('#fbBorrower','please leave your feedback on the borrower here');
	populateElement('#fbLender','please leave your feedback on the lender here ..');
	populateElement('#fbItem','please leave your feedback on the item here ..');
	populateElement('#fbMessage','please type your message here');
	populateElement('#personalisedMessage','if you would like to personalise your response type your message here');
	populateElement('#paypal','please enter your Paypal e-mail here');
	populateElement('#itemsLend','find all items to lend ..');
	populateElement('#reason','  please type in your reason here ..');
	populateElement('#print','  We have set up a circle for London Photographer’s on Ecomodo and would like you to join.');
	populateElement('#people','  find people by name or e-mail address ..');


});*/

/****
 * Function to hide/show a specified div element
 ****/
function toggleDiv(divid){
    if(document.getElementById(divid).style.display == 'block'){
        document.getElementById(divid).style.display = 'none';
    }else{
        document.getElementById(divid).style.display = 'block';
    }
}

/****
 * Function to put some default text into an input box. 
 * The default text is put back in if no text is entered
 ****/

function populateElementfocus(which, defvalue) {
        if ($(which).val() == defvalue) {
            $(which).val("");
            $(which).css({ "color": "#64705B" });
        } 
    }
        
function populateElementblur(which, defvalue) {
        if ($.trim($(which).val()) == "") {
            $(which).val(defvalue);
            $(which).css({ "color": "#64705B" });
        }
        }

/**** 
 * Another function to hide/show a div element
 ****/
function divToggle(theDiv,theState) {
    if(document.getElementById) {
        swapDiv = document.getElementById(theDiv);
        swapDiv.style.display = theState;
        swapDiv.style.position = 'absolute';
        swapDiv.style.zindex = '100';
    }
}

// IE6 Background Hover Flicker Fix
try {
    document.execCommand('BackgroundImageCache',false,true);
}catch(ignoreme){
		
}

/****
 * Opens the map popup to display an item on the map.
 ****/
function openMapPopup( itemID )
{
    openBrowser('ViewOnMap_V2.html?itemID=' + itemID, 560, 620);
}

/****
* Opens the charity popup
****/
function openCharityPopup() {
    openBrowser('CharitySearch.aspx', 519, 598);
}

/****
* Opens the giftaid popup
****/
function openGiftAidPopup(charityNo) {
    openBrowser('CharityGiftaid.aspx?id=' + charityNo, 519, 598);
}

/****
 * Opens the help popup relevant to context.
 ****/
function openHelpPopup(title, topics)
{
    
    openBrowser('../pages/popup_help.aspx?help=' + title + '&topics=' + topics, 519, 598);//was 517 and 598 to suit ie and ff but broke in chrome & safari
}

/****
* Open a new browser window
* The function checks if there's already a window open. If there is, then it's re-used and brought to the front.
* Inputs:
*      mypage  - The url of the page you want to open in the window
*      height  - The height of the window you're opening
*      width   - The width of the window you're opening
****/
function openBrowser(mypage, height, width) 
{

	var myname = 'myBrowser';
	var myWin;
	var pcgsize = 75;

    // Gets the height and width of the current browser window
    var intHeight = $(window).height();
	var intWidth = $(window).width();

    // This just works out a top and left position for the window so it appears in the middle of the currently open window when it opens.
	var wint = Math.round(	(intHeight - height)/5  );
	var winl = Math.round(	(intWidth - width)/2 );
	
	// Sets the window properties
	winprops = 'height='+height+',width='+width+',top='+wint+',left='+winl+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no'
	
	// Check if the window is already open or not
 	if ( !myWin || myWin.closed )
 	{	
 	    // Open a new window
		myWin = window.open(mypage, myname, winprops)
		myWin.focus();
	}
	else
	{
	    // Re-use the existing window.
  		myWin.location.href = myPage;
	  	myWin.focus();
	}
	//return false;
}



/****
 * Toggles a panel (div) up or down
 ****/
function closePanel(panelID)
{
    var node = $('#'+panelID);
    
    if( node.css('display') == 'block')
        $('#'+panelID).slideUp('slow');
    else 
        $('#'+panelID).slideDown('slow');
}

/****
 * Changes a chunk of text into an editable input box
 ****/
function changeToEdit(which, editID, inputType)
{
    $(which).remove();
    var currText = $('#' + editID).html();

    switch (inputType) {
        case 'textLarge':
            $('#' + editID).replaceWith('<input type="text" class="inputLarge" value="' + currText + '" />');
        case 'textSmall':
            $('#' + editID).replaceWith('<input type="text" class="inputSmall" value="' + currText + '" />');
        case 'textarea':
            $('#' + editID).replaceWith('<textarea class="inputText">' + currText + '"</textarea>');
    }
}

/****
* Function to add the newly input tag to the tags list on object_viewObject_AddItem_Description.html
****/
function addNewTag(which)
{
    // Get the new value from the page
    var newVal = $('#txt_newTag').val();

    // Append it to the list of tags
    $('#tagList').append($([
            '<li>',
                '<a href="#" onclick="removeTag(this); return false;" class="deleteTag">Delete</a>',
                newVal,
            '</li>'
        ].join('')));

    // Empty the box and close it.
    $('#txt_newTag').val('');
    $('#newTag').slideUp('slow', function()
    {
    	$('#lnk_addTag').slideDown('slow');
    });

    // Don't know whether you want to do an AJAX callback here to save the new tag, 
    // or have it added to a hidden field on the page that is submitted with the rest of the page.
}

/****
 * Function to remove a tag from the list on object_viewObject_AddItem_Description.html
 ****/
function removeTag(which)
{
    $(which).parent().remove();

    // Don't know whether you want to do an AJAX callback here to remove the new tag, 
    // or have it added to a hidden field on the page that is submitted with the rest of the page.
}




/****
 * Slides the charity and good cause panels up and down on object_viewObject_AddItem_Price.html
 ****/
function updateCharity(which)
{
    switch (which.value) {
        case 'charity':
            $('#pnl_causes').slideUp('slow', function()
            {
                $('#pnl_charity').slideDown('slow');
            });
            break;
        case 'cause':
            $('#pnl_charity').slideUp('slow', function()
            {
                $('#pnl_causes').slideDown('slow');
            });
            break;
		default:
           	if (which.value == 'free')
           	$('#txt_cost').val('0.00');
           	$('#pnl_charity').slideUp('slow');
           	$('#pnl_causes').slideUp('slow');
           	break;
    }
}

function viewOptions(which)
{
	switch (which.value) {
		case 'everyone':
			$('.myCircles').fadeOut('slow');
			$('.myFriends').fadeOut('slow');
			break;
        case 'hidden':
			$('.myCircles').fadeOut('slow');
			$('.myFriends').fadeOut('slow');
			break;
		case 'circles':
		    $('.myFriends').fadeOut('slow', function() {
		        $('.myCircles').fadeIn('slow');
		    });
		    break;
		case 'friends':
		    $('.myCircles').fadeOut('slow', function() {
		        $('.myFriends').fadeIn('slow');
		    });
		    break;
}
}

/****
 * Function to add new options to a drop down on object_viewObject_AddItem_Price.html
 ****/
function updateDropDown(dropID, newOption)
{
    $('#'+dropID).append('<option value="' + newOption + '">' + newOption + '</option>');
}


/****
 * Function to check all boxes are ticked on the terms page object_viewObject_AddItem_Terms.html
 ****/
function enableFinish()
{
    if ($('#chk_termsLend:checked').length == 1 && $('#chk_termsInsure:checked').length == 1)
        $('#btn_finish').attr('disabled', '');
}

/****
 * Checks if new selected from the drop down and show the new label box.
 ****/
function checkLocationlabel(which) {
	if (which.value == "new") {
		$('#txt_newLabel').val('');
		$('#newLabel').slideDown();
    } else {
        $('#newLabel').slideUp();
    }
}


function sendMsg(panelNum, userID)
{
	var msg = $('#textarea' + panelNum).val();

	// need to do some kind of callback so DB knows what's happening
	$.ajax({
		type: 'POST',
		data: 'userID=' + userID + '&msg=' + escape(msg),
		url: '../Callbacks/SendMsg.aspx',
		success: function(msg)
		{
			$('#messages' + panelNum).prepend(msg);
			$('#msgBox' + panelNum).slideUp('slow', function()
			{
				$('#txtSendMsg' + panelNum).slideDown('slow');
				$('#textarea' + panelNum).val('');
			});
		}
	});
}
