/* Author: keith@vool.ie
 * for Touring Ireland
 */

google.load('maps', '2');
//global def map
var map;

// set to true when a info ballon is opened, false when closed
var balloon = false;

//icons array
var giconStyle=[];

//county zoom area array
var countyCoords =[];

// Define the elements for jQuery
var sections  ;
var loading  ;
var content ;
var topToggleImg;
var bottom ;
var msgBox ;
var msgBoxInner;
var adTypes = 4 ; // TODO this to be ref'ed from db

// pano 
var panorama = null;

function defineIcons() { // MAP ICONS
	//Create an icon for the clusters
	iconCluster = new GIcon();
	iconCluster.image = "/mapData/icons/bars.png";
	//iconCluster.shadow = "http://googlemapsbook.com/chapter7/icons/cluster_shadow.png"; //TODO fix this
	iconCluster.iconSize = new GSize(26, 25);
	//iconCluster.shadowSize = new GSize(22, 20);
	iconCluster.iconAnchor = new GPoint(13, 25);
	iconCluster.infoWindowAnchor = new GPoint(13, 1);
	iconCluster.infoShadowAnchor = new GPoint(26, 13);

	//default icon
	//create an icon for the pins [master]
	iconSingle = new GIcon();
	iconSingle.image = "/mapData/icons/default.png";
	iconSingle.iconSize = new GSize(32,32);
	//iconSingle.shadowSize = new GSize(55, 32);
	iconSingle.iconAnchor = new GPoint(6, 20);
	iconSingle.infoWindowAnchor = new GPoint(6, 1);
	iconSingle.infoShadowAnchor = new GPoint(13, 13);

	//fetch icons
	var getIconString = '/mapData/iconStyles.php?v=44m';$
	//retrieve the points
	var request = GXmlHttp.create();
	request.open('GET', getIconString, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var iconStyles;
			var iconSizes;
			var jscript = request.responseText;

			eval(jscript);
			//create styles
			for (i in iconStyles) {
				var thisCat2 = iconStyles[i].cat2ID;
				
				giconStyle[thisCat2]=new Array();
				
					for (j in iconSizes){ // adtyle sizes
					// try to clone an icon -ok
				giconStyle[thisCat2][iconSizes[j].adTypeID] = new GIcon(iconSingle);
				
				giconStyle[thisCat2][iconSizes[j].adTypeID].iconSize = new GSize(iconSizes[j].iconSize.split(",")[0] , iconSizes[j].iconSize.split(",")[1]);
				
				giconStyle[thisCat2][iconSizes[j].adTypeID].image = iconStyles[i].icon;
					
				}
			}
		//once the styles have loaded - update the markers 
		updateMarkers();
		} else {
		}
	}
	request.send(null);

}

/*
 * Global Functions
 */

// checks that a string is not null "" etc.
function hasValue(theString) {
    if(theString === "null" || theString === "" || theString === null) {
        return false;
    } else {
        return true;
    }
}
    
//show loading bar
function showLoading() {
    loading
    .css({visibility:"visible"})
    .css({opacity:"1"})
    .css({display:"block"})
    ;
}

//hide loading bar
function hideLoading() {
    loading.fadeTo(1000, 0);
    jQuery( "input:submit", ".login" ).button();
}

function searchPage() {
}
    
function chkBoxChanged() {
    updateMarkers();    //this can probally be removed and updateMap added to chk bx click ? .k
}

// this functions zooms to a county, long lat and zoom
    function zoomToCounty(a) {
        map.setCenter(new GLatLng(countyCoords[a].lng,countyCoords[a].lat), 8);
        window.location.hash = "!/"+countyCoords[a].countyName;
        document.title = countyCoords[a].countyName;
    }
// This function zooms in or out
// its not necessary to check for out of range zoom numbers, because the API checks
function mapZoom(a) {
    map.setZoom(map.getZoom() + a);
}

// Debuging - wrapper func to stop firebug logs borking this script
var Logger = new
function() {
    this.log = function(str) {
        try {
            console.log(str);
        } catch(e) {
            // do nothing
        }
    };
};
    


function getLoc(position) {
	initLat = position.coords.latitude;
	initLng = position.coords.longitude;
	initZoom = 12;
	map.setCenter(new GLatLng(initLat, initLng), initZoom);

}
// check if element exists
 function elementExists(element) {
    while (element) {
        if (element == document) {
            return true;
        }
        element = element.parentNode;
    }
    return false;
}
/*
 * End Global Functions
 */


function initialize() {
	// Define the elements for jQuery
 sections = $("#menu li, #logo");
 loading = $("#loading");
 msgBox = $("#msg");
 msgBoxInner = $("#msgBoxInner");
 content = $("#topPanelInner");
 topToggleImg = $("img#toggleTop");
 botToggleImg = $("img#toggleBot");
 bottom = $("#botPanelInner");
//var contentWrap = $("#topPanel");
	
    map = new GMap2(document.getElementById("map"));
    
      GEvent.addListener(map, "load", function() {
      showDivs();
   });


// do html5 geoloaction stuff
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(getLoc);
	}

    map.setCenter(new GLatLng(initLat, initLng), initZoom);
    //GLog.write(initLat+" | "+ initLng);
    
    // The following line makes the map Earth-enabled by adding the
    // "Earth" button to the map type control.  Note that you still
    // need to add a map type control (GMapTypeControl,
    // GMenuMapTypeControl, or GHierarchicalMapTypeControl) to the
    // the map (as is done below) for the "Earth" button and the rest
    // of the map type buttons to show up at all.
    map.addMapType(G_SATELLITE_3D_MAP);
   // map.addControl(new GHierarchicalMapTypeControl());
    //map.addControl(new GLargeMapControl());

    // fetch and define the icon styless
    var iconCluster; // these need to be global ?
    var iconSingle;
    defineIcons();

    // get the county zoom coords
    getCountyCoords();
    // update the markers  @ startup);

//Update map on moveend
	GEvent.addListener(map,'moveend', function() {
		if(!balloon) {
			updateMarkers();
		}
	});
	
	   GEvent.addListener(map, "move", function() {
        checkBounds();
      });

          // The allowed region which the whole map must be within
      var allowedBounds = new GLatLngBounds(new GLatLng(51,-13), new GLatLng(56,-5));
      
      // If the map position is out of range, move it back
      function checkBounds() {

        // Perform the check and return if OK
        if (allowedBounds.contains(map.getCenter())) {
          return;
        }
        // It`s not OK, so find the nearest allowed point and move there
        var C = map.getCenter();
        var X = C.lng();
        var Y = C.lat();

        var AmaxX = allowedBounds.getNorthEast().lng();
        var AmaxY = allowedBounds.getNorthEast().lat();
        var AminX = allowedBounds.getSouthWest().lng();
        var AminY = allowedBounds.getSouthWest().lat();

        if (X < AminX) {X = AminX;}
        if (X > AmaxX) {X = AmaxX;}
        if (Y < AminY) {Y = AminY;}
        if (Y > AmaxY) {Y = AmaxY;}
        map.setCenter(new GLatLng(Y,X));
      }
    

    //Manage click events
    sections.click( function() {
        //show the loading bar
        showLoading()
        $(sections).removeClass('active');
        $(this).addClass('active');
               // GLog.write(this.id);

        //load selected section
        switch(this.id) {

            case "search":
            	content.slideUp();
				window.location.hash = "!/search";
                if(!$('#topPanelInner .page-cont').hasClass('search')) {
                    content.load("/includes/pages/search.php");
                    searchPage();
                }
                hideLoading();
                content.slideDown();
                break;

            case "about":
                content.slideUp();
                window.location.hash = "!/about";
                content.load("/includes/pages/about.php", hideLoading);
                content.slideDown();
                break;
                
           case "list":
                content.slideUp();
                window.location.hash = "!/list";
                content.load("/includes/pages/list.php", function() {
                listPage();
                hideLoading();
                content.slideDown();
               });
                break;
                
            case "login":
                content.slideUp();
                window.location.hash = "!/login";
                content.load("/includes/pages/login.php", function() {
                    jQuery( "input:submit", ".login" ).button();
                    hideLoading();
                });
                content.slideDown();
                break;
            case "faqs":
                content.slideUp();
                window.location.hash = "!/faqs";
                content.load("/includes/pages/faq.php", function() {
                    faqPage();
                    hideLoading();
                });
                
                content.slideDown();
                break;

            case "logo":
                content.slideUp();
                window.location.hash = "!/";
                content.load("/includes/pages/home.php", hideLoading);
                content.slideDown();
                break;

            case "signup":
                //open in new window
                window.location ='/dashboard/registration.php';
                break;
            case "logout":
                //open in new window
                window.location = '/dashboard/home.php?doLogout=true';
                break;
            case "dashboard":
                //open in new window
                window.location = '/dashboard/home.php';
                break;
            case "contact":
                content.slideUp();
                window.location.hash = "!/contact";
                content.load("/includes/pages/contact.php", hideLoading);
                content.slideDown();
                break;
            default:
                //hide loading bar if there is no selected section
                hideLoading();
                break;
        }
    });
    topToggleImg.click( function() { 
    	// toggle the content        
        content.toggle("slow");
        // toggle the image
        if ($(this).hasClass('up')) {
            $(this).removeClass('up').addClass('down');
            $(this).attr("src","/img/toggleDown.png");
        } else if ($(this).hasClass('down')) {
            $(this).removeClass('down').addClass('up');
            $(this).attr("src","/img/toggleUp.png");
        }
    });
    
    botToggleImg.click( function() {   
    	// toggle the content    
            bottom.toggle("slow");
        // toggle the image
        if ($(this).hasClass('up')) {
            $(this).removeClass('up').addClass('down');
            $(this).attr("src","/img/toggleDown.png");
        } else if ($(this).hasClass('down')) {
            $(this).removeClass('down').addClass('up');
            $(this).attr("src","/img/toggleUp.png");
        }
    });


    //jQuery nav accordians
    // Accordion
    // set the cat accortian
    jQuery('#nav').accordion({
        active: false,
        header: 'h3',
        navigation: true,
        event: 'click',
        autoHeight: false,
        collapsible: true,
		clearStyle: true,        
        animated: 'easeslide'
    });
    // set the cat accortian
    jQuery('#mapOpts').accordion({
        active: false,
        header: 'h3',
        navigation: true,
        event: 'click',
        autoHeight: false,
        collapsible: true,
        animated: 'easeslide'
    });

    

    // add the click action to map opt checkbotopxs
    // :checkbox might have some issues with ie ? jq
    jQuery('#nav :checkbox').click(chkBoxChanged);
    //the counties zoom select
    $('select#zoomCounty').selectmenu({width:99});
    $('select#setMapType').selectmenu({width:99});
    
    // list page selects
    $('select#listCat1').selectmenu({width:200});
    $('select#listCat2').selectmenu({width:200, style:'dropdown'});


}



/*
 * Gmap functions
 *
 */

function updateMarkers() {
	map.clearOverlays();
    //create the boundry for the data to provide
    //initial filtering
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var getBounds = 'ne=' + northEast.toUrlValue()
    + '&sw=' + southWest.toUrlValue()

    //get the selected checkboxs
    var allVals = [];

    $('#nav :checked').each( function() {
        //get the cat 1 val
        var myCat1ID = $(this).parents("ul:first").attr('class');
        //get the cat 2 val
        var myCat2ID = $(this).parents("li:first").attr('class');
        //allVals.push(myCat1ID+"-"+myCat2ID);
        allVals.push(myCat2ID);
    });$
    //check  that there is at least 1 check boxes selected, if not dont do anything
    // TODO in the future maybe default options ?,
    
if(displayAD || allVals.length > 0){
	
	if(displayAD){
		var getURLString = '/mapData/mapPoints.php?displayAD='+displayAD+'&v=1';	
		//reset the displayAD
		displayAD = null;
	} else if (allVals.length > 0){
        var getCats =  allVals.join("&cat2[]=");
        var getURLString = '/mapData/mapPoints.php?'+getBounds+'&cat2[]='+getCats+'&v=1';    
}
   
        //log the URL for testing
       //GLog.writeUrl(getURLString);

        //retrieve the points
        var request = GXmlHttp.create();
        request.open('GET', getURLString, true);
        request.onreadystatechange = function() {
            if (request.readyState == 4) {

                var jscript = request.responseText;
                var points;
                var pointsCount = 0;
                eval(jscript);
                
                //count the points
                for (i in points) {
                  pointsCount ++;
                }
                
                    //remove the existing points
                    map.clearOverlays();
                //create each point from the list
                for (i in points) {
                    // these are the wrong way round ! ti fukup
                    var point = new GLatLng(points[i].lng,points[i].lat);
                    var marker = createMarker(point,points[i]);
                    //add new points
                    map.addOverlay(marker);
               }
if(pointsCount == 1) { // onlyh one marker// single marker - open it !
                    GEvent.trigger(marker,"click");
                }
               
                            if (pointsCount == 0){
                   msgBox.html('<div class="infoMsg" id="msgBoxInner">Nothing found in this area <br/> Try zooming out</div>' );
                   msgBox.css({opacity:"0"})
                   msgBox.css({visibility:"visible"});
					//    msgBox.fadeIn(400).delay(800).fadeOut(400)
					msgBox.fadeTo('slow', 1).delay(1000).fadeTo('slow', .5, function() {
					msgBox.html('')	//removeMsgBox();
					});
                  }
            }
        }
        request.send(null);
    }
    updateAds();
    
}

function createMarker(point, thisPoint) {//, name = null) {
if(thisPoint.type=='c') { // is a cluster
		var clusterCount = thisPoint.count;
		var myClusterIcon = iconCluster;
		// php image with  count for cluster !
		myClusterIcon.image = "/mapData/icons/cluster/cluster.php?count="+thisPoint.count;
		var marker = new GMarker(point,{icon:myClusterIcon, title:thisPoint.count+" items in this area, Click to view"});
		
		// add click listener
		GEvent.addListener(marker, 'click', function() {
			//TODO this needs to be fixed to zoom better
			map.setCenter(point,map.getZoom()+1);
			//map.setCenter(point,12);
			//map.zoomIn(point,doContinuousZoom = true, doCenter = true);
		});
	} else { // it is a marker ?
		var marker = new GMarker(point,{icon:giconStyle[thisPoint.cat2][thisPoint.adType], title:thisPoint.adName});
		
           var infoTabs = new Array();
        // got an ad set click function
        GEvent.addListener(marker, 'click', function() {

   // compose the data url
    var getURLString = '/mapData/adData.php?displayAD='+thisPoint.adID+'&v=1';  

      // fetch the data for this point
              //retrieve the points
        var request = GXmlHttp.create();
        request.open('GET', getURLString, true);
        request.onreadystatechange = function() {
            if (request.readyState == 4) {

                var jscript = request.responseText;
                var tabs;
                
                eval(jscript);
                
                //loop through tabs
					for (i in tabs) {
						infoTabs[i] = new GInfoWindowTab(tabs[i].title, tabs[i].data);
					}
					 
					  /*
					   //test for Street  View
					   // this was 90% but borking sometimes
					  
        var testPoint = new GLatLng(thisPoint.lng, thisPoint.lat);  
		var svClient = new GStreetviewClient();

   				svClient.getNearestPanoramaLatLng(testPoint, function (nearest) {
						 if ((nearest !== null) && (testPoint.distanceFrom(nearest) <= 100)) {
						//if(nearest !== null) {
							thisPoint.swLoc = nearest;
							GLog.write('Street View Available');             // Within 100 meters
							GLog.write(' distace to nearest sw - '+ testPoint.distanceFrom(nearest));
						} else {
							GLog.write('Street View Noet Available');        // Not within 100 meters
							//remonve the tab
							var y = 0;
							while (y < infoTabs.length) {
								//console.log(infoTabs[i].name);
								if (infoTabs[y].name == 'Panorama') {
									infoTabs.splice(y, 1);
								} else {
									y++;
								}
							}
						}
					});
					*/
					
	//open the window/tabs
					marker.openInfoWindowTabsHtml(infoTabs);
            }
        }
        request.send(null);


if(!balloon) {//only when we click and the balloon is not open
				// set the url hash
				window.location.hash = "!/display/"+thisPoint.adID;
				document.title = thisPoint.adTitle;
			}
			});
        

	// this is called when an info balloon is closed
		GEvent.addListener(marker, 'infowindowclose', function() {
			balloon = false;
			// remove pano
			 if(panorama) {
				panorama.remove();
				GLog.write("rem pano");
			}
		});

// this is called when an info ballon is opened
			GEvent.addListener(marker, 'infowindowopen', function() {

				balloon = true;
				bounds = map.getBounds();
				botLat = bounds.getSouthWest().lat();
				topLat = bounds.getNorthEast().lat();

				diffLat = topLat - botLat;

				markerLng = marker.getPoint().lng();
				markerLat = marker.getPoint().lat();

				newCenLat = markerLat + (diffLat / 2.5);

				map.setCenter(new GLatLng(newCenLat,markerLng));

				$("#topPanelInner").slideUp();
				

					var streetviewDiv = document.getElementById('pano');
					var panorama = new GStreetviewPanorama(streetviewDiv);
					var myYaw = parseFloat(thisPoint.swYaw);
					var myPitch =  parseFloat(thisPoint.swPitch);
					var myZoom = parseFloat(thisPoint.swZoom);
					var myLoc = new GLatLng(thisPoint.lng, thisPoint.lat); 
					myPOV = {yaw:myYaw,pitch:myPitch,zoom:myZoom};

					panorama.setLocationAndPOV(myLoc,myPOV);
					GEvent.addListener(panorama, 'error', function(errorCode) {
						if (errorCode == 600) { // no street view data - remove the tab
							streetviewDiv.innerHTML= "<div class=\"infoMsg\">Sorry, <br/>There is no Panorama view for this location</div>";
						} else if(errorCode == 603) {
							alert("no flash");
							streetviewDiv.innerHTML= "<div class=\"infoMsg\">Sorry, <br/>You need to have flash installed to view the panorama</div>";
						}
					});

updateCounter(thisPoint.adID);
updateAds(markerLng, markerLat);
			});

    }
    return marker;
} // end createMarker()

function initMarkers() {
    updateMarkers();
}


//fetech the couty zoom areas
function getCountyCoords() {

		var getCoCoordsString = '/mapData/countyCoords.php?v=2.3m';

		var request = GXmlHttp.create();
		request.open('GET', getCoCoordsString, true);
		request.onreadystatechange = function() {
			if (request.readyState == 4) {
				var jscript = request.responseText;
				eval(jscript);
				//create styles
				for (i in counties) {
					// stick the json var into a global var
					countyCoords[i] = counties[i];
				}
			} else {
			}
		}
		request.send(null);
	}

function setMapType(mapType, sel){

	switch(mapType){
		case('1'):
		map.setMapType(G_NORMAL_MAP);
		break;
		case('2'):
		map.setMapType(G_SATELLITE_MAP); 	
		break;
		case("3"):
		map.setMapType(G_HYBRID_MAP); 
		break;
		case("4"):
		map.setMapType(G_PHYSICAL_MAP);
		break;
		case("5"):
		map.setMapType(G_SATELLITE_3D_MAP);
		//alert("todo earth"); 
		break;
	}
}


function searchShowAd(myAdID) {
	displayAD =myAdID;
	updateMarkers();
	window.location.hash = "!/display/"+myAdID;
}




function removeItems(array, item) {
	var i = 0;
	while (i < array.length) {
		if (array[i] == item) {
			array.splice(i, 1);
		} else {
			i++;
		}
	}
	return array;
}

function updateCounter(adID) {

	var counter = '/includes/adView.php?mode=set&id='+adID;

	var request = GXmlHttp.create();
	request.open('GET', counter, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var jscript = request.responseText;
			eval(jscript);
		}
	}
	request.send(null);
}


function updateAds(markerLng, markerLat) {
	// only if adPanel is present
	if(elementExists(document.getElementById("botPanel"))){ 
		
	// init the sections
	ad1 = $('#bot1');
	ad2 = $('#bot2');
	ad3 = $('#bot3');
	ad4 = $('#bot4');
	airport = $('#bot5');
	train = $('#bot6');
	bus = $('#bot7');

	if(markerLng && markerLat) {
		myLng = markerLat ;
		myLat =  markerLng;

	} else {
		myLng = map.getCenter().lat();
		myLat =  map.getCenter().lng();

	}

	var getMapAds = '/mapData/mapAds.php?lat='+myLat+'&lng='+myLng;

	//retrieve the points
	var request = GXmlHttp.create();
	request.open('GET', getMapAds, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
			var ads;
			var jscript = request.responseText;
			eval(jscript);

			ad1.fadeOut( function() {
				ad1.html('<a href="javascript:searchShowAd('+ads[0].adID+')"><img src="/userData/img/'+ads[0].userID+'/'+ads[0].adID+'_a.jpg" height="50px" />'+ads[0].adName+'</a>');
				ad1.fadeIn( function() {
					ad2.fadeOut( function() {
						ad2.html('<a href="javascript:searchShowAd('+ads[1].adID+')"><img src="/userData/img/'+ads[1].userID+'/'+ads[1].adID+'_a.jpg" height="50px" />'+ads[1].adName+'</a>');
						ad2.fadeIn( function() {
							ad3.fadeOut( function() {
								ad3.html('<a href="javascript:searchShowAd('+ads[2].adID+')"><img src="/userData/img/'+ads[2].userID+'/'+ads[2].adID+'_a.jpg" height="50px" />'+ads[2].adName+'</a>');
								ad3.fadeIn( function() {
									ad4.fadeOut( function() {
										ad4.html('<a href="javascript:searchShowAd('+ads[3].adID+')"><img src="/userData/img/'+ads[3].userID+'/'+ads[3].adID+'_a.jpg" height="50px" />'+ads[3].adName+'</a>');
										ad4.fadeIn( function() {
											airport.fadeOut( function() {
												airport.html('<a href="javascript:searchShowAd('+ads[4].adID+')"><img src="/img/site_icons/plane.png" width="12" height="12"/> '+ads[4].adName+'</a>');
												airport.fadeIn( function() {
													train.fadeOut( function() {
														train.html('<a href="javascript:searchShowAd('+ads[5].adID+')"><img src="/img/site_icons/train.png" width="12" height="12"/> '+ads[5].adName+'</a>');
														train.fadeIn( function() {
															bus.fadeOut( function() {
																bus.html('<a href="javascript:searchShowAd('+ads[6].adID+')"><img src="/img/site_icons/bus.png" width="12" height="12"/> '+ads[6].adName+'</a>');
																bus.fadeIn();
															});
														});
													});
												});
											});
										});
									});
								});
							});
						});
					});
				});
			});
		} else {
		}
	}
	request.send(null);
	}
}

function showDivs() { // fade in the div once the gmap stuff is loaded
	//$("#map").fadeIn("slow", function() {
		$("#topWrap").fadeIn("slow", function() {
			$("#botWrap").fadeIn("slow");
		});
	//});
}


// handler for faq page
function faqPage() {
	//Set default open/close settings
	$(".acc_container").hide();
	//Hide/close all containers
	//On Click
	$('.acc_trigger').click(function() {
		if($(this).next().is(':hidden')) {//If immediate next container is closed...
			$('.acc_trigger').removeClass('active').next().slideUp();
			//Remove all .acc_trigger classes and slide up the immediate next container
			$(this).toggleClass('active').next().slideDown();
			//Add .acc_trigger class to clicked trigger and slide down the immediate next container
		}
		return false;
		//Prevent the browser jump to the link anchor
	});
}


	// list just js'avies the list on the list page
	function listPage() {

		//prevent default link action / add custom js call
		//cat list
		$("li.listLink a").click(function(event) {
			event.preventDefault();
			doListPage($(this).attr('id'));
		});
		
		//prevent default link action / add custom js call
		//ad list
		$("a.adListResult").click(function(event) {
			event.preventDefault();
			searchShowAd($(this).attr('id'));
		});
		
		    // list page selects 
    $('select#listCat1').selectmenu({width:200});
    $('select#listCat2').selectmenu({width:200, style:'dropdown'});

     //$(".pagination a").css('color', 'red');
    // set links for pagination
    $(".pagination a").click(function() {
  doListPage($(this).attr("title"),'pg');

});


	}
	
	function listAds(dMyID){
	window.location.hash = "!/list/"+myAdID;
}

// handler for the list page
function doListPage(ID, mode) {

	var dataString = '';
	var locHash = '!/list/';

	if(mode == 'pg') {

		var cat1 = $('#listCat1').val();
		var cat2 = $('#listCat2').val();
		locHash += cat1 + "/" + cat2 + "/" + ID + "/";

		// add the page if given

		dataString += "&cat1=" + cat1 + "&cat2=" + cat2 + "&pg=" + ID;

	} else if(mode == 'cat1DD'){
		var cat1 = $('#listCat1').val();
					locHash += cat1 + "/";
			dataString += "&cat1=" + cat1;
		
		}else {
		

		if($('#listCat1')[0]) {
			var cat1 = $('#listCat1').val();
	//		console.log("got cat1 " + cat1);
			dataString += "&cat1=" + cat1;
			locHash += cat1 + "/";
			


			if($('#listCat2')[0] ) {

				
				var cat2 = $('#listCat2').val();
				//console.log("got cat2 " + cat2);
				dataString += "&cat2=" + cat2;
				locHash += cat2 + "/";
				

			} else {
				locHash += ID + "/";
				dataString += "&cat2=" + ID;
			}

		} else {
			locHash += ID + "/";
			dataString += "&cat1=" + ID;
		}

	}
	
	//console.log("loc hash "+locHash);

	//console.log(dataString);
	


	$.ajax({
		type : "GET",
		url : "/includes/pages/list.php",
		data : dataString,
		beforeSend : function() {

			$('#topPanelInner').addClass('loading');

		},
		success : function(server_response) {
			//alert(1);

			$('#topPanelInner').html(server_response).show();
			//$('span#category_title').html(searchString);

			/* do't think this is used
			 if ($('input#search_input').hasClass("loading")) {
			 $("input#search_input").removeClass("loading");
			 }
			 */

			$('span#searchCount').html($('#searchCountTemp').html());
			//alert($('div.pagination').html());

			$('#result_info').css({
				visibility : "visible"
			}).css({
				opacity : "1"
			});

			// fix the links
			listPage();
				window.location.hash = locHash;

		}
	});


}

/*
function popCat2(cat2){
	
	var dataString = 'catSelect=cat2&' + 'catCode1=' + cat2;
	
	$.ajax({
		type : "GET",
		url : "/includes/ajax/getCats.php",
		data : dataString,
		beforeSend : function() {

			$('#topPanelInner').addClass('loading');

		},
		success : function(server_response) {
			alert(1);

			var obj = document.getElementById('listCat2');
			eval(ajax[index].server_response);
			// Executing the response from Ajax as Javascript co
 
return true;
		}
		
	});


}
*/


