function URLEncode( param ){
// The Javascript escape and unescape functions do not correspond
// with what browsers actually do...
   var SAFECHARS = "0123456789" +  // Numeric
                   "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +  // Alphabetic
                   "abcdefghijklmnopqrstuvwxyz" +
                   "-_.!~*'()";                                    // RFC2396 Mark characters
   var HEX = "0123456789ABCDEF";
   var plaintext = param;
   var encoded = "";
   for (var i = 0; i < plaintext.length; i++ ) {
        var ch = plaintext.charAt(i);
        if(ch == " ") {
           encoded += "+";                         // x-www-urlencoded, rather than %20
        }else if (SAFECHARS.indexOf(ch) != -1) {
           encoded += ch;
        }else {
           var charCode = ch.charCodeAt(0);
           if(charCode > 255){
              encoded += "+";
           }else{
              encoded += "%";
              encoded += HEX.charAt((charCode >> 4) & 0xF);
              encoded += HEX.charAt(charCode & 0xF);
           }
        }
   } // for
   return encoded;
}

function recordStats( sData, el ){

	var $rel = sData;
	var $aData = $rel.split("_");
	var _sRandom = Math.random();
    var sPageUrl = '/beenthere/log_stats_proxy.php?&_r=' + _sRandom;
	$.ajax({
        cache: false  ,
        type:  "GET" ,
        url:   sPageUrl ,
        data:  'listing_id='+$aData[1]+'&type_id='+$aData[2],
		success: function(data){
			window.location = el.href;
		}
    });
    return false;
}

function doSearch(){
	
	var _sRandom = Math.random();
    var sPageUrl = '/beenthere/sorting.php?&_r=' + _sRandom;
    if (this.timer) clearTimeout(this.timer);
    this.timer = setTimeout(function (){
        $.ajax({
           	cache: false  ,
           	type:  "POST" ,
           	url:   sPageUrl ,
           	data:  'current_page='+$('#current_page').val()+'&sort='+$("#sortby").val()+'&oClientId='+$('#oClientId').val()+'&oTypeId='+$('#oTypeId').val()+'&client_popup=true',
          	dataType: "json" ,
           	success: function(data){
				var $response =  eval( data );
				if( $response.response.success ){
					if( $("#generalinfo .reviewbox").size()>0 ){
						var fadeOut = 10;
						$("#generalinfo .reviewbox").each(function(e){
							var fadeOutSeconds = (100 * fadeOut);
							$(this).fadeOut(fadeOutSeconds);
							fadeOut += 1;
						});
						
						$("#generalinfo .reviewbox").each(function(e){
							$(this).remove();
						});
					}
					
					
					if( parseInt($response.response.paging.current_total,10)>0){
						var content;
						var loaded = $response.response.memberInfo.length;
						var ref = 0;
						var topClass = 'reviewbox';
						var expandClass = 'expandcontent';
						
						for(var i=0;i<$response.response.memberInfo.length;i++){
							content = '';
							content += '<div class="'+topClass+'" id="'+topClass+'_'+$response.response.memberInfo[i].id+'">';
							content += '<div class="revcol1">'+$response.response.memberInfo[i].getBasicInfo+'</div>';
							content += '<div class="revcol2"><div class="ratebox">'+$response.response.memberInfo[i].ratingInfo+'</div></div>';
							content += '<div class="revcol3">'+$response.response.memberInfo[i].overAllRating+'</div><div class="clearboth"></div>';
							content += '<div class="'+expandClass+'">';
							content += '<div class="commentbox">'+$response.response.memberInfo[i].commentBox+'</div>';
							content += '<div class="detailedrating">'+$response.response.memberInfo[i].detailedRating+'</div>';
							content += '<div class="usefulbox" id="usefulbox_'+$response.response.memberInfo[i].id+'">'+$response.response.memberInfo[i].getUsefulInfo+'</div>';
							content += '<div class="replybox"><h3>'+listing_title+' replies:</h3><p>'+$response.response.memberInfo[i].getReplyBox+'</div>';
							content += '</div><div class="clearboth"></div></div>';
							var fadeInTime = (100) + (parseInt(i,10)*10);
							$('#generalinfo').append(content).fadeIn(fadeInTime);                
							ref++;
						}	
						
						if($response.response.paging.pagination_html){
							$('#client').empty().html($response.response.paging.pagination_html);
						}
						
						var config ={ headerclass: "expandbox",
									  contentclass: "expandcontent",
									  revealtype: "click",
									  mouseoverdelay: 200,
									  collapseprev: true,
									  defaultexpanded: [],
									  onemustopen: false,
									  animatedefault: false,
									  persiststate: false,
									  toggleclass: ["", ""],
									  togglehtml: [],
									  animatespeed: "200"
									};
						config.cssclass={collapse: config.toggleclass[0], expand: config.toggleclass[1]} //store expand and contract CSS classes as object properties
						config.revealtype=/^(click)|(mouseover)$/i.test(config.revealtype)? config.revealtype.replace(/mouseover/i, "mouseenter") : "click"
						config.htmlsetting={location: config.togglehtml[0], collapse: config.togglehtml[1], expand: config.togglehtml[2]} //store HTML settings as object properties
						config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
						config.onopenclose=(typeof config.onopenclose=="undefined")? function(){} : config.onopenclose //attach custom "onopenclose" event handler
						var lastexpanded={}; //object to hold reference to last expanded header and content (jquery objects)
						var expandedindices=ddaccordion.urlparamselect(config.headerclass) || ((config.persiststate && persistedheaders!=null)? persistedheaders : config.defaultexpanded);
						if (typeof expandedindices=='string') //test for string value (exception is config.defaultexpanded, which is an array)
						expandedindices=expandedindices.replace(/c/ig, '').split(','); //transform string value to an array (ie: "c1,c2,c3" becomes [1,2,3]
						var $subcontents=$('.'+config["contentclass"]);
						if (expandedindices.length==1 && expandedindices[0]=="-1") //check for expandedindices value of [-1], indicating persistence is on and no content expanded
							expandedindices=[];
						if (config["collapseprev"] && expandedindices.length>1) //only allow one content open?
							expandedindices=[expandedindices.pop()] //return last array element as an array (for sake of jQuery.inArray())
						if (config["onemustopen"] && expandedindices.length==0) //if at least one content should be open at all times and none are, open 1st header
							expandedindices=[0];
						
						$('.expandbox').each(function(index){ //loop through all headers
							$(this).attr('headerindex', index+'h') //store position of this header relative to its peers
							$subcontents.eq(index).attr('contentindex', index+'c') //store position of this content relative to its peers
							var $subcontent=$subcontents.eq(index)
							var needle=(typeof expandedindices[0]=="number")? index : index+''; //check for data type within expandedindices array- index should match that type
							if (jQuery.inArray(needle, expandedindices)!=-1){ //check for headers that should be expanded automatically (convert index to string first)
							if (config.animatedefault==false)
								$subcontent.show()
								ddaccordion.expandit($(this), $subcontent, config, false) //Last Boolean value sets 'isuseractivated' parameter
								lastexpanded={$header:$(this), $content:$subcontent}
							}else{
								$subcontent.hide()
								config.onopenclose($(this).get(0), parseInt($(this).attr('headerindex')), $subcontent.css('display'), false);
								ddaccordion.transformHeader($(this), config, "collapse")
							}
						});
						
						$('.'+config["headerclass"]).live("evt_accordion", function(){ //assign custom event handler that expands/ contacts a header
							var $subcontent=$subcontents.eq(parseInt($(this).attr('headerindex'))) //get subcontent that should be expanded/collapsed
							if ($subcontent.css('display')=="none"){
								ddaccordion.expandit($(this), $subcontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
								if (config["collapseprev"] && lastexpanded.$header && $(this).get(0)!=lastexpanded.$header.get(0)){ //collapse previous content?
									ddaccordion.collapseit(lastexpanded.$header, lastexpanded.$content, config, true) //Last Boolean value sets 'isuseractivated' parameter
								}
								lastexpanded={$header:$(this), $content:$subcontent}
							}else if (!config["onemustopen"] || config["onemustopen"] && lastexpanded.$header && $(this).get(0)!=lastexpanded.$header.get(0)){
								ddaccordion.collapseit($(this), $subcontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
							}
						});
		
						$('.'+config["headerclass"]).live(config.revealtype, function(){
							if (config.revealtype=="mouseenter"){
								clearTimeout(config.revealdelay)
								var headerindex=parseInt($(this).attr("headerindex"))
								config.revealdelay=setTimeout(function(){ddaccordion.expandone(config["headerclass"], headerindex)}, config.mouseoverdelay || 0)
							}else{
								$(this).trigger("evt_accordion")
								return false //cancel default click behavior
							}
						});
		
						$('.'+config["headerclass"]).live("mouseleave", function(){
							clearTimeout(config.revealdelay)
						});
						
						if(loaded == ref){//items fully loaded remove the preloader
							//$('#show_hide_preloader').fadeOut(1000, function () {
							//	$(this).empty().hide();
							//});	
						}			
					}
				}else{
            	   	$('#show_hide_preloader').fadeOut(1000, function () {
                       $(this).empty().hide();
                   	});
				}	    
            }
        });
    },200);
}

$(document).ready(function(){
        
        $('a[rel*="comments_"]').live("click",function(){
			if( !$(this).attr("show") ){
                $(this).html("Hide Comments");
                $(this).attr("show","show"); 
            }else{
                $(this).html("Show Comments");
                $(this).removeAttr("show");
            }

            var $comments = $(this).attr("rel");
            $('a[rel*="comments_"]').each(function(index,html){// if you click show comments and open another comments then need to set previous clicked to Show Comments 
                if( $comments !== $(this).attr("rel") ){
                   $(this).html("Show Comments");
                }            
            });
        });
		
	    $('.usefulbox input[type="radio"]').live("click", function(e){
		
            var $sPlaceHolder = $(this).attr('id');
            var $aPlaceHolder = $sPlaceHolder.split("_");
            var $divPlaceHolder = $(this).parents()[0].id;
            
            $('#'+$divPlaceHolder).empty().html('Please wait...');
    		var _sRandom = Math.random();
            var _postValue = $(this).val();
            var sPageUrl = '/beenthere/useful_proxy.php?&_r=' + _sRandom;
            if (this.timer) clearTimeout(this.timer);
            this.timer = setTimeout(function (){
                $.ajax({
                   	cache: false  ,
                   	type:  "POST" ,
                   	url:   sPageUrl ,
                   	data:  'review_id='+$aPlaceHolder[2]+'&useful='+_postValue,
                  	dataType: "json" ,
                   	success: function(data){
                       var $response =  eval( data );
                       if( $response.response.success ){
                       		if($response.response.useful_response){
    							$('#useful_'+$aPlaceHolder[2]).empty().html($response.response.useful_response);
                       		}

                       		$('#'+$divPlaceHolder).fadeIn(1000, function () {
                                $(this).html('<hr />Thank you for submitting your opinion.');
                            });

                           	if(!$.cookie("beenthere_rated_"+$aPlaceHolder[2])){
                           		$.cookie("beenthere_rated_"+$aPlaceHolder[2] ,$aPlaceHolder[2], { path: '/', expires: 7 }); 
                         	}	
    				   }else{
                    	   	$('#'+$divPlaceHolder).fadeIn(1000, function () {
                               $(this).html('<hr />Invalid request. Please try again');
                           	});
    				   }    
                    }
                });
            },200);	   
        });
		
		$("#sortby").change(function(){
			$("#current_page").val('0');
			doSearch();
			return false;
		});
		
		$(".apagination").live("click",function(e){
			$("#current_page").val($(this).attr('rel'));
			doSearch();
		});
		
		
});


