/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
var SERVER_PATH = "Templates/store-locator/storeSearch.php";
var IMAGE_PATH = "Templates/shared/images/";
var resultInfo = new Array();
var hasMore = false;
var searching_type;

var locations_for_directions = new Array();

$(document).ready(function(){
   if(location.hash.length > 0){
       specificStore = location.hash.substring(1).split(",",2);
       //onLoadDirections(specificStore[0],specificStore[1]);
        
       $('#city').val(specificStore[1]);
       $('#state').val(specificStore[0]);
       search();        
   }
   else if($('#zipSearch').val() != "Search by Zip Code"){
       search();
   }
   else if($('#city').val() != "Search by City"){
	   search();
   }
});
/********************* 
 * Added in after the fact
 *********************/
function onLoadDirections(state,city){
    $.ajax({
        url: SERVER_PATH+"?getSpecific=1&city="+city+"&state="+state+buildRefinedRequest(),
        type: "GET",
        cache: false,
        success: function(json){
            html = '';
            if(json == ''){return;}

            locationData = evalJSON(json);
           storeInfo = locationData['storeInfo'];

           html += "<p class='info'>";
           addressData = locationData['addressInfo'];
           html += addressData['address1'] + "<br />";
           if(addressData['address2'] != ''){
               html += addressData['address2'] + "<br />";
           }
           html += addressData['city'] + ", " + addressData['state'] + " " + addressData['zip']+"<br />";
           if(storeInfo['phone'] != ''){
                html += storeInfo['phone']+"<br />";
           }
           if(storeInfo['hours'] != ''){
                html += storeInfo['hours'];
           }
           html += "</p>";
           infoString = html;
           infoString = "To: <p class='name'>" +locationData['company']+" "+locationData['name']+"</p>"+ infoString;
           infoString = escape(infoString);

           // Helps fix a slight bug for odd addresses
           addressPart1 = addressData['address1'].split('&');
           addressPart1 = addressPart1[0];
           addressPart2 = addressData['address2'].split('&');
           addressPart2 = addressPart2[0];

           toAddress = "address="+addressPart1+"&city="+addressData['city']+"&state="+addressData['state']+"&zipcode="+addressData['zip'];

           //window.location.href = "http://www.mapquest.com/maps?"+toAddress;
           /*toAddress = escape(toAddress);

           showStepTwo(locationData['coords']['lat'],locationData['coords']['long'],infoString,toAddress);
           $('#backToResults').html("<a name='snapTo'></a>");
           window.location = "#snapTo";*/
        }
    });
}

function search(){
    // Validate form fields
    zipcode = $.trim($('#zipSearch').val());
    city = $.trim($('#city').val());
    state = $.trim($('#state').val());

    if(zipcode != '' && zipcode != 'Search by Zip Code'){
        getLocByZipcode(zipcode);
    }
    else if((city != '' && city != "Search by City") && state != ''){
        getLocByCity(city,state);
    }
    else if((city == "Search by City") && state != '')
	{
		getLocByCity(city,state);
	}
    else{
        alert('Please fill out info');
        return;
    }
}

function evalJSON(json){
    return eval("("+json+")");
}

function getLocByZipcode(zipcode){
	searching_type = 'zip';
    $.ajax({
        url: SERVER_PATH+"?searchDistance=1&zipcode="+zipcode+buildRefinedRequest(),
        type: "GET",
        cache: false,
        success: function(json){
            processSearchData(json);
        }
    });
}

function getLocByCity(city,state){
	searching_type = 'city_state';
    $.ajax({
        url: SERVER_PATH+"?searchDistance=1&city="+city+"&state="+state+buildRefinedRequest(),
        type: "GET",
        cache: false,
        success: function(json){
            processSearchData(json);
        }
    });
}


function getPage(page,lat,longitude,state)
{
	$(".print_icon").css("display","none");
	
	if (searching_type == 'zip')
	{
		url = SERVER_PATH+"?searchDistance=1&lat="+lat+"&long=" + longitude + "&page=" + page + buildRefinedRequest();
	}
	else
	{
		url = SERVER_PATH+"?searchDistance=1&lat="+lat+"&long=" + longitude + "&page=" + page + "&city=&state=" + state + buildRefinedRequest();
	}
	
    refined = buildRefinedRequest();
    $.ajax({
        url: url,
        type: "GET",
        cache: false,
        success: function(json){
            processSearchData(json);
        }
    });
}

function processSearchData(data){
    jsonData = evalJSON(data);
    showStepOne(jsonData['locations']);
    $('#multipleListing').append(buildPagination(jsonData,jsonData['currentPage']));
    load('gmap');
    show_locs(jsonData);
    
}

function buildPagination(data,currentPage)
{    
	state = data['locations'][0]['addressInfo']['state'];
    html = '';
    html += "<div class='pagination'>";
    coords = data['startCoords'];
    nextPage = currentPage + 1;
    previousPage = currentPage - 1;
    if(currentPage > 0){
    	if (searching_type == 'zip')
    	{
    		html += "<a href='javascript:void(0)' onclick='getPage("+ previousPage +","+coords['lat']+"," +  coords['long'] + ");'>&lt;&lt;previous</a>";
    	}
    	else
    	{
    		html += "<a href='javascript:void(0)' onclick='getPage("+ previousPage +","+coords['lat']+"," +  coords['long'] + ",\"" + state + "\");'>&lt;&lt;previous</a>";
    	}
    }
    if(currentPage > 0 && hasMore){
        html += " | ";
    }
    if(hasMore){
    	if (searching_type == 'zip')
    	{
    		html += "<a href='javascript:void(0)' onclick='getPage("+nextPage +","+coords['lat']+"," +  coords['long']+");'>next&gt;&gt;</a>";
    	}
    	else
    	{
    		html += "<a href='javascript:void(0)' onclick='getPage("+nextPage +","+coords['lat']+"," +  coords['long']+",\"" + state + "\");'>next&gt;&gt;</a>";
    	}
    }
    html += "</div>";

    /*********************
     * Set global variables for current page info
     *
     */
    resultInfo['currentPage'] = currentPage;
    resultInfo['long'] = coords['long'];
    resultInfo['lat'] = coords['lat'];

    return html;
}

function buildRefinedRequest(){
    var refined = new Array();

    if($('#el').is(':checked')){
        refined['estee'] = 1;
    }
    if($('#lancome').attr('checked') == true){
        refined['lancome'] = 1;
    }
    if($('#clinique').attr('checked') == true){
        refined['clinique'] = 1;
    }
    if($('#fr').attr('checked') == true){
        refined['formalwear'] = 1;
    }
    requested = '';
    for(var i in refined){
        requested += "&has"+i+"=1";
    }
    return requested;
}



function hasSpecialItems(arrayItems){
    for(i in arrayItems){
        arrayItem = arrayItems[i];
        if(arrayItem == 1){
            return true;
        }
    }
    return false;
}

function showStepOne(locations){
    $('#multipleListing').children().remove();
    html = '';
    hasMore = false;
    if (locations == undefined)
    {
    	locations.length = 0;
    }
    
    
    if(locations.length > 5){
        locations.splice(5,locations.length - 5);
        hasMore = true;
    }
    if(locations.length == 0){
        html += "<p class='noResults'>Your search yielded no results within 100 miles.</p>";
    }
    else{
        for(var i in locations){
        	locationData = locations[i];
            html += "<div class='item'>";
            letter = String.fromCharCode("A".charCodeAt(0) + (locationData['resultNumber']%26));
            if(locationData['resultNumber'] > 25){
                letter = String.fromCharCode("A".charCodeAt(0) + (locationData['resultNumber']/25) - 1) + letter;
            }
            displayLetter = letter+")";
            displayName = locationData['company']+"<br />"+locationData['name'];
            //html += "<div class='name' style='text-indent:0;'><span class='letter'><img src=\"http://www.google.com/mapfiles/marker" + letter + ".png\" />"+"</span><a href='javascript:void(0)' onclick='GEvent.trigger(markers["+i+"],\"click\")' class='nameText'>"+displayName+"</a><br class='clear' /></div>";
            html += "<div class='name' style='text-indent:0;'><span class='letter'><img src=\"http://www.google.com/mapfiles/marker" + letter + ".png\" />"+"</span>"+displayName+"<br class='clear' /></div>";
            
            if (locationData['grand_opening_status'] != "")
            {
         	   html += "<div class='grand_opening'>" + locationData['grand_opening_status'] + "</div>"; 
            }
            
            storeInfo = locationData['storeInfo'];

               if(hasSpecialItems(storeInfo['atLocation'])){
                    atLocation = storeInfo['atLocation'];
                    html += "<div class='atLocation'>";
                    html += "At this location:<br />";
                    if(atLocation['clinique'] == 1){
                        html += "<img src='"+IMAGE_PATH+"consumer/location/clinique.jpg' alt='Clinique'/><br/>";
                    }
                    if(atLocation['orderclinique'] == 1){
                    	html += "<img src='"+IMAGE_PATH+"consumer/location/order-clinique.gif' alt='Order Clinique'/><br/>";
                    }
                    if(atLocation['estee'] == 1){
                        html += "<img src='"+IMAGE_PATH+"consumer/location/estee-lauder.jpg' alt='Est&eacute;e Lauder'/><br/>";
                    }
                    if(atLocation['formalwear'] == 1){
                        html += "<img src='"+IMAGE_PATH+"consumer/location/formalwear-rental.jpg' alt='Formalwear Rental'/>";
                    }
                    html += "</div>";
               }
               htmlp1 = html;
               html = '';

               html += "<p class='info'>";
               
               html += "<a href=\"/loc/" + locationData['storeID'] + "\"><img src=\"/images/local-pages/btn-see-store-details.gif\" alt=\"see store details\"/></a>";
               html += "</p>";
               
               html = htmlp1 + html;
               
               html += "<br  class='clear''/>";
               html += "</div>";
               
               /*
               html += "<p class='info'>";
               addressData = locationData['addressInfo'];
               html += addressData['address1'] + "<br />";
               if(addressData['address2'] != ''){
                   html += addressData['address2'] + "<br />";
               }
               html += addressData['city'] + ", " + addressData['state'] + " " + addressData['zip']+"<br />";
               if(storeInfo['phone'] != ''){
                    html += storeInfo['phone']+"<br />";
               }
               if(storeInfo['hours'] != ''){
                    html += storeInfo['hours'];
               }
               html += "</p>";
               infoString = html;
               infoString = "To: <p class='name'>" +locationData['company']+" "+locationData['name']+"</p>"+ infoString;
               infoString = escape(infoString);

               html = htmlp1 + html;

               // Helps fix a slight bug for odd addresses
               addressPart1 = addressData['address1'].split('&');
               addressPart1 = addressPart1[0];
               addressPart2 = addressData['address2'].split('&');
               addressPart2 = addressPart2[0];

               if($.trim(addressPart2) != ""){
                   addressPart2 += ",";
               }
               else{
                   addressPart2 = "";
               }
               toAddress = "address="+addressPart1+"&city="+addressData['city']+"&state="+addressData['state']+"&zipcode="+addressData['zip'];
               mapsExternal = "http://www.mapquest.com/maps?"+toAddress;
               
               html += "<br  class='clear''/>";
               html += "<a href='javascript:void(0)' class='directions' onclick='showStepTwo(\"" + locationData['coords']['lat'] + "\",\"" + locationData['coords']['long'] + "\",\"" + infoString + "\",\"" + toAddress + "\"," + i + ");'>Directions</a>";

               html += "<br  class='clear''/>";
               html += "</div>";
               */
        }
    }
    $('#multipleListing').prepend(html);
    $('#searchStepTwo').css('display','none');
    $('#searchStepOne').css('display','block');
}

function showStepTwo(toLat, toLong, toInfo, toAddress,location_index)
{
	loc = locations_for_directions[location_index];
	
    $('#searchStepOne').css('display','none');
    $('#searchStepTwo').css('display','block');
    clearLoading();
    $('#backToResults').html("<a href='javascript:void(0)' onclick='getPage("+resultInfo['currentPage'] +","+resultInfo['lat']+"," +  resultInfo['long']+",\"" + loc['addressInfo']['state'] + "\");'>&lt;&lt; Back to search results</a>");

    load('gmap2');

    data = new Array();
    data['locations'] = new Array();
    data['locations'][0] = loc;
    
    show_locs(data);

    $('#toInfo').html(unescape(toInfo));
    $('#destAddress').val(toAddress);
    $('#startLat').val(toLat);
    $('#startLong').val(toLong);
}

function setTextZip(element,hasFocus){
	currentValue = $(element).val();
	if(hasFocus == 1){
		if(currentValue == 'Search by Zip Code'){
			$(element).val('');
		}
	}
	else{
		if(jQuery.trim(currentValue) == ''){
			$(element).val('Search by Zip Code');
		}
	}
}
function setTextCity(element,hasFocus){
	currentValue = $(element).val();
	if(hasFocus == 1){
		if(currentValue == 'Search by City'){
			$(element).val('');
		}
	}
	else{
		if(jQuery.trim(currentValue) == ''){
			$(element).val('Search by City');
		}
	}
}

function resetFields(selector){
    $('#streetDir').val('');
    $('#cityDir').val('');
    $('#stateDir').val('');
    $('#zipDir').val('');
    mapDirections.clear();
    $(".print_icon").css("display","none");
}

function getDirections(){
    startingLat = $('#startLat').val();
    startingLong = $('#startLong').val();
    startingAddress = $('#destAddress').val();
    startingAddress = unescape(startingAddress);

    //$('body').append(startingAddress);
    //startingAddress = "";

    destString = "to: "+startingLat+", "+startingLong;
    //destString = "to: "+startingAddress;
    fromString = "from: "+$('#streetDir').val()+", "+$('#cityDir').val()+", "+$('#stateDir').val()+", "+$('#zipDir').val();
    query = destString +" "+ fromString;
    setLoading();
    setTimeout("mapDirections.load(\""+query+"\");  $(\".print_icon\").css(\"display\",\"block\");",200);
    // show directions thickbox
}

function onGDirectionsLoad(){
    //setTimeout("switchContent();",200);
    clearLoading();
}

function onGDirectionsFail(){
    setError();
    $(".print_icon").css("display","none");
}

function switchContent(){
    directionsHTML = document.getElementById('directionsPanel');
    directionsHTML = directionsHTML.innerHTML;
    $('#TB_ajaxContent').html(directionsHTML);
}

function setError(){
    mapDirections.clear();
    requestStatus = mapDirections.getStatus();
    errorString = "There was an error processing your request. <br />Either the starting address and/or the destination address could not be resolved. <br />Error code: "+requestStatus['code'];
    $('#directionsError').html("<p style='color:#AA0000;'>"+errorString+"</p>");
    $('#directionsPanel').html(" ");
    document.location.hash = "directionsError";
}

function setLoading(){
    mapDirections.clear();
    $('#directionsPanel').html("<table class='loading'><tr><td>Loading Directions...<br /><img src='Templates/shared/images/loadingAnimation.gif' alt='Loading...'/></td></tr></table>");
}

function clearLoading(){
    $('#directionsPanel').html("");
}

