var $j = jQuery.noConflict();

/********************************************
 * Move to folder links frame checkbox valdation
 ********************************************/
function selectAll()
  {   	
    var folderCount=document.getElementById("popup_move_to_folders").contentWindow.iFolderCount;
    var frameRef=document.getElementById("popup_move_to_folders").contentWindow.document;
    if(document.getElementById("moveToFolderSelectAll").checked)
    {
      for(var i=0;i<folderCount;i++)
      {
          if(frameRef.getElementById("movetofolder_"+i))
            frameRef.getElementById("movetofolder_"+i).checked=true;
      }
    }
    else
    {
      for(var i=0;i<folderCount;i++)
      {
          if(frameRef.getElementById("movetofolder_"+i))
            frameRef.getElementById("movetofolder_"+i).checked=false;         
      }
    }
  }

/****************************************
 * Email validation
 *****************************************/
function checkEmail(sEmail)
{
    var emailRegEx1 = /^([\w\-\.]+)@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,4}))$/;
    if (sEmail.match(emailRegEx1))
    { 
      return true;
    }   
    else
    {
      return false;
    }   
}

function completeRate(i,id)
{ 	
  for(var j=1;j<=5;j++)
  { 
    if(j<=i)
    {           
      document.getElementById("vote_"+id+"_"+j).style.backgroundPosition="";    
      document.getElementById("vote_"+id+"_"+j).className="rate rated";     
    }
    else
    {
      document.getElementById("vote_"+id+"_"+j).style.backgroundPosition="";    
      document.getElementById("vote_"+id+"_"+j).className="rate";     
    }
  }   
}

function highlight_stars(id, star, do_highlight,flag)
{   
  var sUrl="";
  var iCount=0;
  
  if(flag=='all')
  {
      for (var i = 1 ; i <= star ; i++)
      {     
        if(do_highlight)                       
           document.getElementById('rateall_'+id+'_'+i).style.backgroundPosition="left 32px";
        else         
          {
            if(document.getElementById('rateall_'+id+'_'+i).className=="rate rated")                     
              document.getElementById('rateall_'+id+'_'+i).style.backgroundPosition="left 0px";
            else                     
              document.getElementById('rateall_'+id+'_'+i).style.backgroundPosition="left 16px";            
            }       
      }        
  }
  else
  { 
      for (var i = 1 ; i <= star ; i++)
      {
        if(do_highlight)              
           document.getElementById('vote_'+id+'_'+i).style.backgroundPosition="left 32px";        
        else               
          {
            if(document.getElementById('vote_'+id+'_'+i).className=="rate rated")
                //$j('#vote_'+id+'_'+i).css({backgroundPosition: 'left: 0px'});     
               document.getElementById('vote_'+id+'_'+i).style.backgroundPosition="left 0px";
            else
              document.getElementById('vote_'+id+'_'+i).style.backgroundPosition="left 16px";
            }
            
      }
  }
}
 

/*function changeBackgroundColors(urlid,color)
{
   $j('#div_'+urlid).css({backgroundColor:"#"+color});     
   $j("#div_"+urlid+" .RndTopOneTops b").css({backgroundColor:"#"+color});
   $j("#div_"+urlid+" .RndBottomOneTops b").css({backgroundColor:"#"+color});
}
*/
/*INDIVIDUAL CHECKBOX CLICKED IN MYFOLDERS*/
 /* function linkSelect(obj) {    
    var urlid=obj.id;
    var urlId=urlid.split("_");
    var urlid_id=urlId[1];    
    if(obj.checked)
    {
         changeBackgroundColors(urlid_id,'FFFFCC');
    }
        else{     
    changeBackgroundColors(urlid_id,'FFFFFF');
      
      if($j('#contentSelectAll').attr("checked") === true)
        $j('#contentSelectAll').attr("checked", false) ;
        
      }     
    };
*/
/*function contentSelectAll()
      {     
        if(document.getElementById("contentSelectAll").checked)
        {       
          for(var i=0;i<10;i++)
          {
            if(document.getElementById("checkbox_"+i))
            {               
                $j('#checkbox_'+i).attr("checked", true) ;            
                changeBackgroundColors(i,'FFFFCC');
            }
          }
        }
        else
        {
          for(var i=0;i<10;i++)
          {
            if(document.getElementById("checkbox_"+i))
            {
                document.getElementById("checkbox_"+i).checked=false;       
                changeBackgroundColors(i,'FFFFFF'); 
            }
          }
        }       
      }       
*/
function publicRating(select)
{ 
  searchPublicLinks(select.selectedIndex+1); 
}

function searchPublicLinks(page)
{ 
  $j.ajax({          
        url: '/publicSearch/displayPublicSearchLinks?pagenum='+page,
        cache: false,
        data: "keyword="+$j('#searchMyHistoryField').val(),   
        success: function(html){
        $j("#searchPublicLinks").html(html);                
        }
  });
}

/*TELL A FRIEND BLOCKUI*/
function tellAfriend()
{
  $j.ajax({ 
                url: '/faq/tellAFriend', 
                cache: false,                 
                success: function(html){                 
              $j('#contactDiv') .html(html);
 		$j("#contactDiv").modal({						      
		      minWidth: 330,
		      opacity:60,      
		      overlayCss: {backgroundColor:"#FFF"}
	        });
                  
            /*  $j.blockUI({ message: $j('#contactDiv'),              
                css: 
                { 
                  padding:          '1px',
                  margin:              0,
                  width:               '330px', 
                  top:                    '20%', 
                  left:                   '35%', 
                  textAlign:          '', 
                  color:                '#000', 
                  border:             '2px solid #FF9933',
                  backgroundColor:  'white',
                  cursor:               'default'
              }
               });
              $j('#closeUI').click(function() { 
                $j.unblockUI(); 
                return false; 
                 
        });              
        $j('#exitUI').click(function() { 
                $j.unblockUI(); 
                return false; 
        });        */

      
        
        $j('.mailtoButton').hover(function() {
        $j(this).attr("src","/images/bu_submit_o.gif");
      }, function() {
      $j(this).attr("src","/images/bu_submit.gif");
    });    
        
          $j('.cancelButton').hover(function() {
        $j(this).attr("src","/images/bu_cancel_o.gif");
      }, function() {
      $j(this).attr("src","/images/bu_cancel.gif");
    });    
        
        
        $j('#submitButton').click(function () {   
          
        var sYourName   = $j("#yourName").val().replace(/^\s+|\s+$/g, '');   
        var sYourEmail   = $j("#yourEmail").val().replace(/^\s+|\s+$/g, '');    
        var sFirstName    = $j("#firstName").val().replace(/^\s+|\s+$/g, '');   
        var sFirstEmail    = $j("#firstEmail").val().replace(/^\s+|\s+$/g, '');         
        var sSecondName  = $j("#secondName").val().replace(/^\s+|\s+$/g, ''); 
        var sSecondEmail  = $j("#secondEmail").val().replace(/^\s+|\s+$/g, '');           
        var sThirdName    = $j("#thirdName").val().replace(/^\s+|\s+$/g, ''); 
        var sThirdEmail    = $j("#thirdEmail").val().replace(/^\s+|\s+$/g, '');                   
        var sEmailMessage = $j("#emailMessage").val().replace(/^\s+|\s+$/g, '');  
        var iValidEmailCount = 0;
      
      if(sYourName == "")
      {
        $j("#yourName").focus();
        alert("Please fill in your first name");
        return false;
      } 
      else if(sYourEmail == "")                                            
      { 
        alert("Please fill in the email address");
        $j("#yourEmail").focus();
        return false;
      }
      else if(checkEmail(sYourEmail) == false)
      {
        alert("Please check email address.");
        $j("#yourEmail").focus();
        return false;
      }
    
      if(sFirstName != "" || sFirstEmail !="")
      {
        if(sFirstEmail == "")                                            
        { 
          alert("Please fill in the email address");
          $j("#firstEmail").focus();
          return false;
        }
        else if(checkEmail(sFirstEmail) == false)
        {
          alert("Please check email address.");
          $j("#firstEmail").focus();
          return false;
        }
        else
          iValidEmailCount++;
      }
    
      if(sSecondName != "" || sSecondEmail !="")
      {
        if(sSecondEmail == "")                                            
        { 
          alert("Please fill in the email address.");
          $j("#secondEmail").focus();
          return false;
        }
        else if(checkEmail(sSecondEmail) == false)
        {
          alert("Please check email address.");
          $j("#secondEmail").focus();
          return false;
        }
        else
          iValidEmailCount++;
      }
    
      if(sThirdName != "" || sThirdEmail !="")
      {
        if(sThirdEmail == "")                                            
        { 
          alert("Please check email address.");
          $j("#thirdEmail").focus();
          return false;
        }
        else if(checkEmail(sThirdEmail) == false)
        {
          alert("Please check email address.");
          $j("#thirdEmail").focus();
          iValidEmailCount++;
          return false;
        }
        else
          iValidEmailCount++;
      }
      
      if(sEmailMessage == "")
      {
        $j("#emailMessage").focus();
        alert("Please fill in the message.");
        return false;
      } 
    
      if(iValidEmailCount == 0)
      {
        alert("Please fill in the email address.");
        $j("#firstEmail").focus();
        return false;
      }         
               
        $j.ajax({ 
                url: '/faq/mailToFriend', 
                cache: false, 
                data: "yourName="+$j('#yourName').val()+"&yourEmail="+$j('#yourEmail').val()+"&firstName="+$j('#firstName').val()+"&firstEmail="+$j('#firstEmail').val()+"&secondName="+$j('#secondName').val()
                +"&secondEmail="+$j('#secondEmail').val() +"&thirdName="+$j('#thirdName').val()+"&thirdEmail="+$j('#thirdEmail').val()+"&emailMessage="+$j('#emailMessage').val(),                              
                success: function(html){                
                  $j('#errormessage') .html(html);                                        
                }
                
            });    
             
  });                                       
                }
            }); 
}


function paginationForMyHistory(select)
{ 
  searchHooeey((select.selectedIndex+1));
}

function siteSearchPagination(select)
{ 
  searchSite((select.selectedIndex+1));
}		
function refresh()
{
	   $j.unblockUI(); 
        return false;     
}

function searchHooeey(page)
{ 
	/*strip the special characters*/
	var searchString = strpSpecialChar($j('#searchMyHistoryField').val());	
	setCurrentView('F');
  $j.ajax({         
        url: '/searchHistory/searchResultsMyHistory?pagenum='+page,
          cache: false,
          data: "keywords="+encodeURIComponent(searchString),    
        success: function(html){
        $j("#searchHooeeyId").html(html);                
        }
  });
}

function searchValidation(keyword)
{
	if(keyword == '')
	{
	 alert('Please enter something to search for!');
	 return false;
	}
	location.href="searchSite/index?keyword="+encodeURIComponent(keyword);
}

function searchSite(page)
{   
   /*strip the special characters*/
	var searchKeyword = strpSpecialChar($j('#searchMyHistoryField').val()); 	
  $j.ajax({         
        url: '/searchSite/searchResultsSite?pagenum='+page,
          cache: false,
          data: "keywords="+encodeURIComponent(searchKeyword),   
        success: function(html){
        $j("#searchSiteDiv").html(html);                 
        }
  });
}

/* Search the myhistory */
function searchMyHistory()
{       
  if(document.getElementById("searchMyHistoryField").value.replace(/^\s+|\s+$/g, '')!="")
  {
    /*strip the special characters*/
  	var searchKeyword = strpSpecialChar($j('#searchMyHistoryField').val());     	
    if(document.getElementById("searchMyHistoryId").checked)
    {     
      location.href="/searchHistory/index?keyword="+encodeURIComponent(searchKeyword);      
    }
    else if(document.getElementById("siteSearchId").checked)
    {     
      location.href="/searchSite/index?keyword="+encodeURIComponent(searchKeyword);
    } 
  }   
}

/*Function for strip special characters*/
function strpSpecialChar(searchKeyword)
{	
   return  searchKeyword.replace(/[^a-zA-Z 0-9]+/g,'');
}

$j(document).ready(function(){  
     
  /* AJAX LOADING INDICATOR*/
 $j("body").append(' <div id="ajaxbusy"> <P><img src="../../images/ajax-loader-1.gif"></p> </div>  ');
 
 
 $j('#ajaxbusy').css({
   display:"none"
   }); 
    
    
    $j(document).ajaxStart(function(){
   $j('#ajaxbusy').centerInClient().show();
     }).ajaxStop(function(){
   $j('#ajaxbusy').centerInClient().hide();
    });
 
 /* AJAX LOADING INDICATOR ENDS*/ 

PEPS.rollover.init();       
  
});
  
PEPS = {};

PEPS.rollover =
{
   init: function()
   {
      this.preload();
      
      $j(".ro").hover(
         function () { $j(this).attr( 'src', PEPS.rollover.newimage($j(this).attr('src')) ); },
         function () { $j(this).attr( 'src', PEPS.rollover.oldimage($j(this).attr('src')) ); }
      );
   },

   preload: function()
   {
      $j(window).bind('load', function() {
         $j('.ro').each( function( key, elm ) { $j('<img>').attr( 'src', PEPS.rollover.newimage( $j(this).attr('src') ) ); });
      });
   },
   
   newimage: function( src )
   {
      return src.substring( 0, src.search(/(\.[a-z]+)/) ) + '_o' + src.match(/(\.[a-z]+)/)[0];
   },
   
   oldimage: function( src )
   {
      return src.replace(/_o/, '');
   }
};                


/*Centers the selected items in the browser window.*/
  
$j.fn.centerInClient = function(options) {
    /// <summary>Centers the selected items in the browser window. Takes into account scroll position.
    /// Ideally the selected set should only match a single element.
    /// </summary>    
    /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>    
    /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow 
    ///  and attached to the body element to ensure proper absolute positioning. 
    /// Be aware that this may cause ID hierachy for CSS styles to be affected.
    /// </param>
    /// <returns type="jQuery" />
    var opt = { forceAbsolute: false,
                container: window,    // selector of element to center in
                completeHandler: null
              };
    $j.extend(opt, options);
   
    return this.each(function(i) {
        var el = $j(this);
        var jWin = $j(opt.container);
        var isWin = opt.container == window;

        // force to the top of document to ENSURE that 
        // document absolute positioning is available
        if (opt.forceAbsolute) {
            if (isWin)
                el.remove().appendTo("body");
            else
                el.remove().appendTo(jWin.get(0));
        }

        // have to make absolute
        el.css("position", "absolute");

        // height is off a bit so fudge it
        var heightFudge = isWin ? 2.0 : 1.8;

        var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
        var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;

        el.css("left", x + jWin.scrollLeft());
        el.css("top", y + jWin.scrollTop());

        // if specified make callback and pass element
        if (opt.completeHandler)
            opt.completeHandler(this);
    });
}
  
