// this check can be removed once all page use minify
var ua = null;
var b = null;
var css_browser_selector = function() {ua=navigator.userAgent.toLowerCase();is=function(t){return ua.indexOf(t) != -1;};h=document.getElementsByTagName('html')[0];b=(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?'gecko ff2':is('firefox/3')?'gecko ff3':is('gecko/')?'gecko':is('opera/9')?'opera opera9':/opera\s(\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('chrome')?'chrome webkit safari':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'';os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';var c=b+os+' js'; h.className += h.className?' '+c:c;}();

//////////////////////////////////////////////////
//	Identify Search Current-Page:
		var $cur_page = 1;
// Previous Batch-Set:
		var $prev_rec = -1;
// Disregard Set:
// Next Batch-Set:
		var $next_rec = 1;
//	Default Search-pattern:
		var $default	= '_';


/*Start mobile.js import*/
var cat_array = [];
var subcat_array = [];
var _back_button_active = false;
/*Canadian Provinces structure:*/
var cnt_ca = {'ab' : 'Alberta', 'bc' : 'British Columbia', 'mb' : 'Manitoba', 'nb' : 'New Brunswick', 'nl' : 'New Foundland', 'ns' : 'Nova Scotia', 'nt' : 'NorthWest Territories', 'nu' : 'Nunavut', 'on' : 'Ontario', 'pe' : 'Prince Edward Island', 'qc' : 'Quebec', 'sk' : 'Saskatchewan', 'yt' : 'Yukon Territory'};

/*United States structure (functional):*/
var cnt_us = {'ak' : 'Alaska', 'al' : 'Alabama', 'ar' : 'Arkansas', 'az' : 'Arizona', 'ca' : 'California', 'co' : 'Colorado', 'ct' : 'Connecticut', 'dc' : 'District Of Columbia', 'de' : 'Delaware', 'fl' : 'Florida', 'ga' : 'Georgia', 'hi' : 'Hawaii', 'ia' : 'Iowa', 'id' : 'Idaho', 'il' : 'Illinois', 'in' : 'Indiana', 'ks' : 'Kansas', 'ky' : 'Kentucky', 'la' : 'Louisiana', 'ma' : 'Massachusetts', 'md' : 'Maryland', 'me' : 'Maine', 'nc' : 'North Carolina', 'nh' : 'New Hampshire', 'ri' : 'Rhode Island', 'sc' : 'South Carolina', 'sd' : 'South Dakota', 'tx' : 'Texas', 'wy' : 'Wyoming'};

var countries = {'124' : 'Canada', '840' : 'United States'};

var cnt_ = {'124' : cnt_ca, '840' : cnt_us};

function function_exists (function_name) {
	if (typeof function_name == 'string'){
		return (typeof this.window[function_name] == 'function');
	} else{
		return (function_name instanceof Function);
	}
}

function show_search_form(){
	$('.results,.map').hide();
	$('.search').show();
	$('#soff').val(0);
	if ($('input:radio[name=search_type]:checked').val() == 'basic'){
		$('.adv').hide();
		$('.basic').show();
	}
	else{
		$('.basic').hide();
		$('.adv').show();
	}
	
	// reset drop downs
	if (_back_button_active && $('#sub_categories').val())
	{
		// reset
		$('#sub_categories').val(0);
	}
	else if (_back_button_active && $('#categories').val())
	{
		// reset
		$('#categorie').val(0);
	}
	else if (_back_button_active && $('#locations').val())
	{
		// reset
		$('#locations').val(0);
	}
	else if (_back_button_active && $('#sections').val())
	{
		// reset
		$('#sections').val(0);
	}
}

function hide_search_form(){
	$('.results,.map').hide();
	$('.search').hide();
	$('.basic').hide();
	$('.adv').hide();
}

function show_results(){
}

function explode (delimiter, string, limit) {
	var emptyArray = { 0: '' };

		// third argument is not required
	if ( arguments.length < 2 ||
		typeof arguments[0] == 'undefined' ||				typeof arguments[1] == 'undefined' ) {
			return null;
		}

	if ( delimiter === '' ||				delimiter === false ||
		delimiter === null ) {
			return false;
		}
	if ( typeof delimiter == 'function' ||
		typeof delimiter == 'object' ||
		typeof string == 'function' ||
		typeof string == 'object' ) {
			return emptyArray;		}

	if ( delimiter === true ) {
		delimiter = '1';
	}
	if (!limit) {
		return string.toString().split(delimiter.toString());
	} else {
				// support for limit argument				var splitted = string.toString().split(delimiter.toString());
		var partA = splitted.splice(0, limit - 1);
		var partB = splitted.join(delimiter.toString());
		partA.push(partB);
		return partA;		}
}

//////////////////////////////////////////////////
//	Clear Google-Map Interface:
function clearGoogleMap()
{
	if (markerArray !== undefined)
	{
		for (var idx = 0; idx < 16; idx++)
		{
			if (markerArray[idx] === undefined)
			{
				break;
			}
			markerArray[idx].setMap(null);
			markerArray[idx].setVisible(false);
		}
	}

	markerArray = [];
	infoWindow.close();
}

//////////////////////////////////////////////////
//	Purge HTML-Tags from Source:
function purgeHTML( message ){
	return( message.replace( /\&amp\;/g, "&" ).replace( /\&nbsp\;/ig, " " ).replace( /([\t]*)/g, "" ).replace( /\<br \/>/ig, "\n" ).replace( /(<([^>]+)>)/ig, "" ).replace( /([\ \ ]+)/g, " " ).replace( /([\;]+)/g, ";\n" ) );
}

//////////////////////////////////////////////////
//Sanatize Response Text:
function validateResponse( message ){
	var sql_query = /SQL-Query/;
	var warning = /Warning/;
//Validate SQL-Query:
	if( message.search( sql_query ) != -1 ){
			alert( purgeHTML( message.replace( sql_query, "SQL-Query:\n" ).replace( warning, "\nWarning:\n" ).replace( /([\\']+)/g, "'" ).replace( /([\\']+)/g, "/" ) ) );
			return( false );
		}
//Validate Warning:
	if( message.search( warning ) != -1 ){
			alert( purgeHTML( message.replace( warning, "\nWarning\n" ).replace( /([\\']+)/g, "'" ).replace( /([\\']+)/g, "/" ) ) );
			return( false );
		}
	return( true );
}

//////////////////////////////////////////////////
//	Reset Web-Form element(s):
function reset_WebForm(){
	$('#sections option').remove();
	$('#sections').html('Select '+_state_label_);
	$('#locations option').remove();
	$('#categories option').remove();
	$('#sub_categories option').remove();
	$('listings').html("");
}

//////////////////////////////////////////////////
//	Populate Web-Form element(s):
function addOption( selectbox, value, text ){
	var selected = 0;
	switch( selectbox ){
		case '#country':
			if( value == _cnt_id_ ){
				selected = 1;
			} 
			break;
		case '#sections':
			if( value == _loc_id_ ){
				selected = 1;
			} 
			break;
		case '#locations':
			if( value == _ctv_id_ ){
				selected = 1;
			} 
			break;
		case '#categories':
			if( value == _cat_id_ ){
				selected = 1;
			} 
			break;
		case '#sub_categories':
			if( value == _scat_id_ ){
				selected = 1;
			} 
			break;
		default:
			break;
	}
	
	if (selected)
	{
		$(selectbox).append('<option value="'+value+'" selected="selected">'+text+'</option>');
		return value;
	}
	else
	{
		$(selectbox).append('<option value="'+value+'">'+text+'</option>');
		return -1;
	}
}

/*Checkbox Single-Select behavior:*/
function singleSelect( checkObj ){
	chkBoxes = document.selections.elements[checkObj.name];
	if( checkObj.checked === true ){
		for( var i = 0; i < chkBoxes.length; i++ ){
			ele = chkBoxes[i];
			if( ele.type == 'checkbox' ){
				if( ele.value == checkObj.value ){
					ele.checked = true;
				} 
				else { 
					ele.checked = false;
				}
			}
		}
	}
}

var Url = {
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
	},
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = 0;
		var c1 = 0;
		var c2 = 0;
		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
}


//////////////////////////////////////////////////
//	Get 'Initiailze MySQL/PHP & AJAX' component(s):
function initialize(){
}
function initialize_new(){
}

function finalize()
{
}

$(document).ready(function()
{
	$('#mapall').click(function(){
		map_Addresses(_lat_, _lng_);
		$('#listings_map').show();
	});

	finalize();
});

/*Get 'Article' element(s):*/
/*Get 'Advertisement' element(s):*/
function get_Advertisement(){
  reset_Profiles();
  
  var $advertise = '';
  $advertise += '      <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="640" height="480">';
  $advertise += '        <param name="movie" value="/content/multimedia/swf_files/' + _tld_ + '_' + _exclude_ + 'advertise.swf" />';
  $advertise += '        <param name="quality" value="high" />';
  $advertise += '        <embed src="/content/multimedia/swf_files/' + _tld_ + '_' + _exclude_ + 'advertise.swf" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="640" height="480"></embed>';
  $advertise += '      </object>';
  $('#advertisement_container, #services_interface').show();
}

/*Get 'Multimedia' element(s):*/
function get_Multimedia(playVideo){
  reset_Profiles();
  var params = { allowScriptAccess:"always", allowfullscreen:"true" };
  //the id of the embed object - what we'll use to get a reference to the player using getElementById()
  var atts = { id: "corporate_video" };
  swfobject.embedSWF(_youtube_url_, "youtube_video", "450", "365", "8", null, null, params, atts);		
  $('#multimedia_container, #services_interface').show();
}

/*Get 'Promotions' element(s):*/
function get_Promotions(){
  reset_Profiles();
  $('#promotions_container, #services_interface').show();
}

/*Get 'Gallery' element(s):*/
function get_Gallery(){
  reset_Profiles();
  $('#gallery_container, #services_interface').show();
}

/*Get 'Article' element(s):*/
function get_Articles(){
  reset_Profiles();
  $('#editorial_container, #services_interface').show();
}

/*Get 'GoogleMap' element(s):*/
function get_GoogleMapXDXX( $container, $canvas, $address, $profile )
{
  reset_Profiles();
	//alert( "canvas: " + $canvas + " -> " + $address );
	//  Confirms Browse-Compatibility level(s):
  if( GBrowserIsCompatible() ){ geocoder = new GClientGeocoder(); }
		//  GMap2 Configuration(s):
    var map = new GMap2( document.getElementById( $canvas ) );
		//  GMap2 Controller(s):
		//        map.addControl( new GSmallZoomControl() );
    map.addControl( new GSmallMapControl() );
    map.addControl( new GMapTypeControl() );
    map.addControl( new google.maps.LocalSearch() );
    $reference = document.getElementById('reference').value;
		//  Get-Directions element(s):
    var my_dirs = document.getElementById('get_directions');
    var map_dirs = document.getElementById('map_directions');
    map_dirs.innerHTML = '';
		//  Get-Directions Language:
    $language = document.getElementById('language').value;
		//  Map Zoom-level(s):
  	mapZoomLevel = 8;
    if ($reference !== null)
    {
      var mapZoomLevel = 16;
      my_dirs.style.visibility = "visible";
      map_dirs.style.visibility = "visible";
    }
    else
    {
    	map_dirs.style.visibility = "hidden";
    }
    var gdir = new GDirections( map, map_dirs );
    if (geocoder)
    {
      geocoder.getLatLng
      (
        $address,
        function( point ){
          if (! point)
          {
						// alert( "Postal/Zip Code: " + $address + " cannot be found!" );
          }
          else
          {
            $latitude = point.lat().toFixed(5);
            $longitude = point.lng().toFixed(5);
            self.status = $latitude + ' x ' + $longitude;
						//  Map-Marker Object:
            var marker = new GIcon( G_DEFAULT_ICON );
						//  Marker-Object Attribute(s):
            marker.image = "/marker.png";
            marker.iconSize = new GSize( 55, 52 );  //  width/height
            var options ={ icon:marker, clickable:true, draggable:false };
            var mapMarker = new GMarker( point, options);
						//  Containers Visibility-level(s):
            document.getElementById($container).style.visibility = "visible";
            map.clearOverlays();
            map.addOverlay( mapMarker );
            if ($profile != null)
            {
              var html = "<span id='google_info'>" + $profile + "</span>";
              mapMarker.info_window_content = html;
              mapMarker.openInfoWindowHtml( mapMarker.info_window_content, { maxWidth:400 } );
              GEvent.addListener( mapMarker, "click", function(){ map.panTo( point, 2 ) } );
            }
            map.setCenter( point, mapZoomLevel, G_NORMAL_MAP );
						//  Add a local search element:
            if ($reference !== null)
            {
              gdir.load( "from: " + $reference + " to: " + $address, { "locale": $language } );
            }
          }
        }
      );
    }
  }

/*Get 'My Directions' element(s):*/
function get_MyDirections()
{
  if ($('#reference').val())
  {
    show_directions();
  }

  /*$address = document.getElementById('my_directions').value;
  if( $address != '' )
  {
    document.getElementById('reference').value = $address;

  }
  get_GoogleMap(_google_map_,_float_canvas_,_location_,_google_info_);*/
}

/*Get 'Print Coupon' element(s):*/
var auto_print = true;
function print_coupon( url )
{
  var $day = new Date();
  var $id = $day.getTime();
  var $config = "var $coupon" + " = window.open( '', 'coupon', 'toolbar=0,scrollbars=0,directories=0,location=0,status=0,menubar=0,resizable=0,width=600,height=280' );";
  eval( $config );
	if (window.focus)
	{
	  $coupon.focus();
		var container  = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
		    container += '<html xmlns="http://www.w3.org/1999/xhtml"><head>';
		    container += '<link href="/addons/themes/explorer/css/profiler-comments_new-1.css" rel="stylesheet" type="text/css" />';
		    container += '<body class="container">';
		$coupon.document.write( container + document.getElementById('coupon_container').innerHTML + '</body></html>' );
		$coupon.document.close();
	}
  if( auto_print ){ $coupon.print(); }
}


