/*
 * INITIALIZE GENERAL SECTION
 */
document.observe("dom:loaded", function() {

   if ( $('sendPasswordButton') != null ) {
        $('sendPasswordButton').observe('click', forgotPasswordSubmitLinkClick );
   }
   
   if ( $('forgotPasswordLink')!=null ) {
        $('forgotPasswordLink').observe('click', showForgotPasswordOverlay );
   }
   
   if ( $('privacyPolicyLink')!=null ) {
        $('privacyPolicyLink').observe( 'click' , function( event ) { showPrivacyPolicyOverlay( event ); } );
   }
   
   if ( $('sendToFriendLink')!=null ) {
        $('sendToFriendLink').observe( 'click' , function( event ) { showSendToFriendOverlay( event ); } );
   }
   
   if ( $( 'sendToFriendSubmitButton' )!=null ) {
        $( 'sendToFriendSubmitButton' ).observe( 'click' , function( event ) { sendToFriendEmail( event ); } );
   }

   if ($('cancelForgotPasswordConfirmationOverlay') != null) {
       $('cancelForgotPasswordConfirmationOverlay').observe('click', hideForgotPasswordConfirmationOverlay);
   }
   
   
});   

/* **************************************
   Class definitions
   ************************************** */
   
function JsonSendToFriendDTO()
{
    this.emailTemplate;
    this.senderName;
    this.senderEmail;
    this.recipientName;
    this.recipientEmail;
    this.subject;
    this.message;
}

function init(centerOnResize) {

	var objectType = typeof centerOnResize;

	if (objectType != 'object') {		
        var setCenterOnResize = new Boolean(true);
        if (centerOnResize == 'False' || centerOnResize == 'false') {
              setCenterOnResize = false;
        }

        if (setCenterOnResize) {
        	document.body.style.height = document.documentElement.scrollHeight > document.viewport.getHeight() ? document.documentElement.scrollHeight + 'px' : document.viewport.getHeight() + 'px';
            onresize = repositionMainContainer;
        }
    }
}

function getAbsY(elm) {
	if (elm.y) return elm.y;
	pos = 0;

	while (elm != null) {
		pos += elm["offsetTop"];
		elm = elm.offsetParent;
	}

	return pos;
}

function submitForm(formObj) {
	// TODO: Probably have a check for netscape or IE here
	formObj.submit();
} // submitForm



// Remove leading and trailing whitespace from a string
function trimWhitespace(string) {
	var newString  = '';
	var substring  = '';
	beginningFound = false;

	// copy characters over to a new string
	// retain whitespace characters if they are between other characters
	for (var i = 0; i < string.length; i++) {

		// copy non-whitespace characters
		if (string.charAt(i) != ' ' && string.charCodeAt(i) != 9) {

			// if the temporary string contains some whitespace characters, copy them first
			if (substring != '') {
				newString += substring;
				substring = '';
			}
			newString += string.charAt(i);
			if (beginningFound == false) beginningFound = true;
		}

		// hold whitespace characters in a temporary string if they follow a non-whitespace character
		else if (beginningFound == true) substring += string.charAt(i);
	}
	return newString;
}

function gotoLink(sel)
{
	window.location = sel.options[sel.selectedIndex].value;
}

/* for navigating from a dropdown box */
function goToPage(theOptionValue){
   location = theOptionValue.options[theOptionValue.selectedIndex].value;
   }

// Clears the search text field when it is given the focus (if user has not entered anything)
var searchText;

function clearSearchText(formfield, text) {
	searchText = text;
	if (formfield.value == searchText) formfield.value = '';
}

// Refills the search text field on blur if it is empty
function fillSearchText(formfield) {
	if (formfield.value == '') formfield.value = searchText;
}
function isDefined(property) {
  return (typeof property != 'undefined');
}

// call init when document finishes loading
if (isDefined(window.addEventListener)) {
   window.addEventListener('load', init, false);
}
else if (isDefined(window.attachEvent)) {
   window.attachEvent('onload', init);
}

// get width of browser
function getInnerWidth(win) {
  var winWidth;
  if (navigator.userAgent.indexOf('Gecko') != -1 && navigator.userAgent.indexOf('Netscape6') == -1) {
    winWidth = win.document.body.clientWidth;
  }
  else if (document.compatMode == "CSS1Compat") {
    winWidth = win.document.documentElement.clientWidth;
  }
  else if (navigator.appName == 'Netscape') {
    winWidth = win.innerWidth;
  }
  else {
    winWidth = win.document.body.clientWidth;
  }
  return winWidth;
}

// write out style for main container
function positionMainContainer() {
   var winWidth = getInnerWidth(window);
   var left = parseInt((winWidth > 807) ? (winWidth - 807) / 2 : 0);

   doc = '<style>#mainContainer { ';
   doc += 'left: ' + left + 'px; ';
   doc += '}';
   document.write(doc + '</style>');
}

function repositionMainContainer() {
   if (document.getElementById) {
      var container = document.getElementById('mainContainer');
      var winWidth = getInnerWidth(window);

      if (document.getElementById('mainContainer'))
      {
      container.style.left = ((winWidth > 807) ? (winWidth - 807) / 2 : 0) + 'px';
	  }
   }
}
function bannerFlash() {
	if (!HasFlash) {
		var divBanner = document.getElementById('bannerID');
		var divBannerMain = document.getElementById('banner');
		
		$(divBannerMain).addClassName('displayNone');
		$(divBanner).addClassName('flashBanner');
		
		divBanner.innerHTML = '<div>We are sorry but Flash plug-in is needed to view some content on this site. If  \
							   you believe you have the flash player installed, first remove it using the Adobe \
							   Flash uninstall program and then reinstall the Flash Player. Please visit \
							   Adobe\'s web site for installation troubleshooting <br />Please click the icon to \
							   download the he latest version of Flash... <br /> \
							   <a target="_blank" href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash"> \
							   <img src="/img/AdobeLogo.GIF" width="88px" height="31px" /> </a> </div>';
		}
}

function handleValidationError(elementId, messages)
{
    var errorMsg = i18nText.translate('E4');
    if (messages.length > 0) {
        errorMsg += "<ul>";
        for (var i = 0; i < messages.length; i++) {
            errorMsg += "<li>"+ messages[i] + "</li>";
        }
        errorMsg += "</ul>";
    }

    $(elementId).removeClassName("error");
    $(elementId).addClassName("validation");
   
    $(elementId).update(errorMsg);
    $(elementId).show();    
}

function handleSystemExceptionError(elementId, message)
{
    var errorMsg = i18nText.translate('E4');
    errorMsg += "<ul><li>"+message+"</li><ul>";

    $(elementId).removeClassName("validation");
    $(elementId).addClassName("error");
    
    $(elementId).update(errorMsg);
    $(elementId).show();
}

function resetFeedbackPanel(elementId)
{
    if ($(elementId) != null) {
    	$(elementId).removeClassName("validation");
    	$(elementId).removeClassName("error");

        $(elementId).update();
        $(elementId).hide();
    }
}

function handleDisplayText(elementId, message)
{
   if (message != null) {
      $(elementId).innerHTML = message;
      $(elementId).show();
   }
}

function clearControl(elementId)
{
  $(elementId).innerHTML = '';
}


function rulesAndRegulationsClick() {

	if ($('banner1') != null) {
		$('banner1').style.display = '';
	}
	
	new Popup('ruleAndRegulationsOverlay',null,{modal:true},{position:'center'});
	$('ruleAndRegulationsOverlay').popup.show(); 
	
	var divElement = document.getElementById('popup_overlay');
    divElement.onclick = function () { $('ruleAndRegulationsOverlay').popup.hide() };
    
    var elements = $$('select'); // implicitly hide select drop downs for browser bug
    for (var i = 0; i < elements.length; i++) {
		 elements[i].hide();
	}	
}

function privatePolicyClick(event) {

	if ($('banner1') != null) {
		$('banner1').style.display = '';
	}

	new Popup('privatePolicyOverlay',null,{modal:true},{position:'center'});
	$('privatePolicyOverlay').popup.show(); 
	
	var divElement = document.getElementById('popup_overlay');
    divElement.onclick = function () { $('privatePolicyOverlay').popup.hide() };
    
    var elements = $$('select'); // implicitly hide select drop downs for browser bug
    for (var i = 0; i < elements.length; i++) {
		 elements[i].hide();
	}
}


function forgotPasswordOverlayClick(event)
{
    new Popup('forgotpasswordOverlay',null,{modal:true},{position:'center'});
	$('forgotpasswordOverlay').popup.show();

    $("popup_overlay").observe('click', function(event) {
        $('forgotpasswordOverlay').popup.hide();
    });
    
    event.stop();
}


function showSendToFriendOverlay( event ) {
    if ( $('sendToFriendOverlay')!=null ) {
    
        Event.stop( event );
        
        $('sendToFriendErrorLabel').innerHTML = "";
    
        $( 'f_subject' ).value = document.title;
        
        if ($('banner1') != null ) {
            $('banner1').style.display = '';
        }
	
        new Popup(
            'sendToFriendOverlay',
            null,
            { modal: true },
            { position: 'center' }
        );     
                    
        $( 'sendToFriendOverlay' ).popup.show();
        
        $( 'popup_overlay' ).onclick = function () {        
            $( 'sendToFriendOverlay' ).popup.hide();
        };        
    }
    
}

function showSendToFriendPopup() {

    $('sendToFriendErrorLabel').innerHTML = "";
    
    $('f_subject').value=document.title;
    
	new Popup('sendToFriendOverlay',null,{modal:true},{position:'center'});
	
	$('sendToFriendOverlay').popup.show();
	
	if($('banner1'))
	{
	    $('banner1').style.display = '';
	}

	var divElement = document.getElementById('popup_overlay');
    divElement.onclick = function () { $('sendToFriendOverlay').popup.hide();};
    
    var elements = $$('select'); // implicitly hide select drop downs for browser bug
    for (var i = 0; i < elements.length; i++)
    {
		 elements[i].hide();
	}	
	return false;
	
}

function showSendToFriendConfirmationPopup(subject,message)
{
	$('sendToFriendOverlay').popup.hide();
	new Popup('sendToFriendConfirmationOverlay',null,{modal:true},{position:'center'});
	$('sendToFriendConfirmationOverlay').popup.show();
	if($('banner1'))
	{
	    $('banner1').style.display = '';
	}
	$('sentSubject').innerHTML=subject;
	$('sentMessage').innerHTML=message;
	var divElement = document.getElementById('popup_overlay');
	divElement.onclick = function () { $('sendToFriendConfirmationOverlay').popup.hide();};
	var elements = $$('select'); // implicitly hide select drop downs for browser bug
	for (var i = 0; i < elements.length; i++)
	{
		elements[i].hide();
	}
}

function sendToFriendEmail( event ) {

    Event.stop( event );
    
    var jsonEmailObject = new JsonSendToFriendDTO();
      jsonEmailObject.emailTemplate = 'SendToFriend';
      jsonEmailObject.senderName = $('f_senderName').value;
      jsonEmailObject.senderEmail = $('f_senderEmail').value;
      jsonEmailObject.recipientName = $('f_friendName').value;;
      jsonEmailObject.recipientEmail = $('f_friendEmail').value;
      jsonEmailObject.subject = $('f_subject').value;
      jsonEmailObject.message = $('f_message').value;

    document.body.style.cursor= 'wait';
    
    new Ajax.Request('/' + locale + '/SendToFriend.json', 
    { 
        method:'get',
        parameters: { useResponseBody: 'true', jsonString: Object.toJSON(jsonEmailObject) },
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON();
            switch(json.type) {
              case "JsonMethodMessage":
                    showSendToFriendConfirmationPopup(jsonEmailObject.subject,jsonEmailObject.message);
                    break;
              case "JsonValidationMessage":
                    handleValidationError('sendToFriendErrorLabel', json.messages)
                    break;
              case "JsonSystemExceptionMessage":
                    handleSystemExceptionError('sendToFriendErrorLabel', json.message);
                    break;
              }
        },
        onFailure: function(){
            handleSystemExceptionError(addressType + 'ErrorPanel', json.message); 
            $('sendToFriendConfirmationOverlay').style.display = 'none';
            $('sendToFriendOverlay').style.display = 'block';
        },
        onComplete: function(){
            document.body.style.cursor= 'default';
        }
     })
}

function sendToFriendOverlayHide()
{
    $('sendToFriendOverlay').popup.hide()
    if($('banner1'))
	{
	    $('banner1').style.display = 'block';
	}
}

function sendToFriendConfirmationOverlayHide()
{
    $('sendToFriendConfirmationOverlay').popup.hide()
    if($('banner1'))
	{
        $('banner1').style.display = 'block';
	}
}
 
var Ex = YAHOO.namespace('desato.paging');

function createPaging(pagingNamespace, containerDiv, pagingDiv, rowsPerPage, itemClassName, itemIdPrefix, pagingFunction, dictionary) 
{
    if ($$('.' + itemClassName).size() > rowsPerPage) {
        // set the dictionary to use for labels
        if (dictionary == null) {
            Ex.dictionary = i18nText;
        } else {
            Ex.dictionary = dictionary;
        }
        Ex.content = $(containerDiv);
        Ex.handlePagination = function (state) {
            var pageItems = $(containerDiv).select('[class="' + itemClassName + '"]');
            pageItems.each(function(item) {
                item.hide();
            });        
            for (var i = state.records[0] + 1; i <= state.records[1] + 1; i++) {
                $(itemIdPrefix + i).toggle();
            }        
            // update the summary now
            var summary = $(pagingDiv).select('div.summary')[0];
            summary.innerHTML = Ex.formatSummary(state);
            
            Ex.paginator.setState(state);
        };
        Ex.formatSummary = function(state) {
        
            var minCurrent = 1;
            var maxCurrent = rowsPerPage;        
            var totalItems = $(containerDiv).select('[class="' + itemClassName + '"]').size();

            if (state != null) {
                minCurrent = state.recordOffset + 1;
                maxCurrent = minCurrent + state.rowsPerPage - 1 > totalItems ? totalItems : minCurrent + state.rowsPerPage - 1;
            } else if (maxCurrent > totalItems) {
                maxCurrent = totalItems;
            }        
            var params =  [minCurrent + ' - ' + maxCurrent, totalItems];
            return Ex.dictionary.formattedTranslate('ViewAllLabel', params);
        };
        
        Ex.paginator = new YAHOO.widget.Paginator({
            rowsPerPage : rowsPerPage,
            totalRecords : $$('[class="' + itemClassName + '"]').size(),
            containers : pagingDiv,
            previousPageLinkLabel: Ex.dictionary.translate('PreviousLabel'),
            nextPageLinkLabel: Ex.dictionary.translate('NextLabel'),
            template : "<div class='pagingItems'>{PreviousPageLink}{PageLinks}{NextPageLink}</div><div class='summary'>" + Ex.formatSummary() + "</div>"
        });
        
        if (pagingFunction != null) {
            Ex.paginator.subscribe('changeRequest', pagingFunction);
        } else {
            Ex.paginator.subscribe('changeRequest', Ex.handlePagination);
        }
        
        Ex.paginator.render();
        var state = Ex.paginator.getState();
        
        var pageItems = $(containerDiv).select('[class="' + itemClassName + '"]');
        pageItems.each(function(item, index) {
            if (index < rowsPerPage) {
                item.show();
            } else {
                item.hide();
            }
        });        
    }
}

/* 
    This function is used to get query string value.
    For example;   
    var queryString = getQueryString();
    var nameOfVar = queryString['nameOfQueryStringAttribute'];
*/

function getQueryString(){
	var qsParm = new Array();
	var q = window.location.search || document.location.hash;
	var query = q.substring(1);
	var parms = query.split('&');
	for (var i=0; i<parms.length; i++) {
		var pos = parms[i].indexOf('=');
		if (pos > 0) {
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			qsParm[key] = val;
		}
	}
	return qsParm;
}

function showPrivacyPolicyOverlay(event) {
    
    if ( $('privacyPolicyOverlay')!=null ) {
    	Event.stop(event);
    	if ($('banner1') != null) {
    		$('banner1').style.display = 'visible';
    	}
        new Popup('privacyPolicyOverlay',null,{ modal: true },{ position: 'center' });
		$('privacyPolicyOverlay').popup.show();
        $( 'popup_overlay' ).onclick = function () {
            $( 'privacyPolicyOverlay' ).popup.hide();
        };
    }    
}

//TODO: We already have 'forgotPasswordSubmitLinkClick' function in campaign and dealerTraining Json files,
//so we need to replace them at some point

function showForgotPasswordOverlay() {
    clearControl('forgotPasswordFeedbackPanel');
    new Popup('forgotPasswordOverlay', null, { modal: true }, { position: 'center' });
    $('forgotPasswordOverlay').popup.show();

    $('forgotPasswordOverlay').select('div.formPanel')[0].show();
    $('forgotPasswordOverlay').select('div.confirmationPanel')[0].hide();
    
    $('popup_overlay').onclick = function() { hideForgotPasswordOverlay(); };
    if ($('popup_closePassword') != null) {
    	$('popup_closePassword').onclick = function() { hideForgotPasswordOverlay(); };
    }
}

function hideForgotPasswordConfirmationOverlay() {
    $('forgotPasswordConfirmationOverlay').popup.hide();
}

function hideForgotPasswordOverlay() {
    $('forgotPasswordOverlay').popup.hide();
}

function forgotPasswordSubmitLinkClick(event) {

    $("forgotPasswordFeedbackPanel").update();
    
    var jsonParam = {
        'email':$('forgotPasswordEmail').value
    }
        
    document.body.style.cursor= 'wait';
    new Ajax.Request('/' + locale + '/ForgotPassword.json', 
      { 
        method:'get',
        parameters: {useResponseBody:'true', jsonString:Object.toJSON(jsonParam)},      
        onSuccess: function(transport){ 
          var json = transport.responseText.evalJSON();  
          switch(json.type) {
              case 'JsonMethodMessage':
                    showForgotPasswordConfirmationOverlay(json.userMessage);
                    break;
              case 'JsonValidationMessage':
                    handleValidationError('forgotPasswordFeedbackPanel', json.messages);
                    break;
              case 'JsonSystemExceptionMessage':
                    handleSystemExceptionError('forgotPasswordFeedbackPanel', json.message);
                    break;
           }
        },
        onFailure: function(){
            handleSystemExceptionError('forgotPasswordFeedbackPanel', json.message); 
        },
        onComplete: function(){
            document.body.style.cursor= 'default';
        }
     });
     
     event.stop();
 }

 function showForgotPasswordConfirmationOverlay(message) {
     
     $('forgotPasswordOverlay').select('div.formPanel')[0].hide();
     
     $('forgotPasswordOverlay').select('div.formPanel')[0].hide();
     $('forgotPasswordOverlay').select('div.confirmationPanel')[0].show();

     $$('#forgotPasswordOverlay div.confirmationPanel div.overlayText')[0].innerHTML = message;
     
     $('forgotPasswordClose').observe('click', function(event) {
         hideForgotPasswordOverlay();
     });
 }

/* 
   Do NOT Delete this function. We are using this function in Framework. It is being used to hide feedback panel 
   of Newslettersubscription widget on CommunityServer blog pages.
*/
 function hideNewsletterFeedbackPanel() {
    var newsletterFeedbackPanelClientId = $('newsletterFeedbackPanelClientId').innerHTML;
    $(newsletterFeedbackPanelClientId).hide();
 }

 /* This function is created to initialize product tabs (Highlights, Variation, Related Videos etc...) on product details page */

function initializeProdTabs() {    
    var myTabs = new YAHOO.widget.TabView( "productTabs" );
}
