// $Id$
var controls = {
  "map_canvas" : "store-map-canvas",
  "map_controls" : "map_controls",
  "map_info" : "map_info",
  "map_error" : "map_error",
  "geocoder" : {
	 "div":"geocode",
	 "address":"edit-address"
  },
  "routectl" : "routectl",
  "map_default" : "map_default",
  "map_store" : "map_store",
  "message_info" : "message_info",
  "map_kml" : "map_kml",
  "count_store" : "count_store"
};

//Global variables definition
var storeDetailURL="";
var clusterHeight = 52;
var clusterWidth = 71;
var address = null;
var displayMgr = null;
var param = null;
var titleSearch = Drupal.t('Your search');
var titleDirection= Drupal.t('Get directions');
var titleItinerary= Drupal.t('Driving direction to');
var libAddr = null;


function getValuesSync(queryUrl, callback) {
    jQuery.ajax({
        url: queryUrl,
        async : false,
        type: "GET",
	    dataType: 'jsonp',
        success: callback
    });
}

function addressSearch() {
	address = jQuery('#' + controls.geocoder.address).val();
	libAddr = Drupal.t('Enter a zip code or a city', getLang());
	if (address != '' && address !=libAddr) {
		showAddress(null,address + " , " + Drupal.settings.storelocator_app.storelocator_default_address);
	} else {
		showAddress(null,Drupal.settings.storelocator_app.storelocator_default_address);
	}
	return false;
}

function parseGeocode(results) {
	var status = results.status;
}
function showAddress(zoom,address) {
	var boundingBox = null;
	new google.maps.Geocoder().geocode( { 'address': address , 'region': Drupal.settings.storelocator_app.storelocator_country_code}, function(results, status) {
		//try geocode
		// if KO => call geocode from server
		
		if (status == google.maps.GeocoderStatus.ZERO_RESULTS) { 
			param = null;
		} else if (status == google.maps.GeocoderStatus.OK) {
			var southWestLat = "";
			var southWestLong = "";
			var northEastLat = "";
			var northEastLong = "";
			if (results[0].geometry.bounds) {
				southWestLat = results[0].geometry.bounds.getSouthWest().lat();
				southWestLong = results[0].geometry.bounds.getSouthWest().lng();
				northEastLat = results[0].geometry.bounds.getNorthEast().lat();
				northEastLong = results[0].geometry.bounds.getNorthEast().lng();	
			} else if (results[0].geometry.viewport) {
				southWestLat = results[0].geometry.viewport.getSouthWest().lat();
				southWestLong = results[0].geometry.viewport.getSouthWest().lng();
				northEastLat = results[0].geometry.viewport.getNorthEast().lat();
				northEastLong = results[0].geometry.viewport.getNorthEast().lng();	
			}
			param = "&parameters[store_bounds]=" + southWestLat;
			param += "," + southWestLong ;
			param += "," + northEastLat;
			param += "," + northEastLong;
			boundingBox = new google.maps.LatLngBounds(
					new google.maps.LatLng(southWestLat, southWestLong),
					new google.maps.LatLng(northEastLat, northEastLong));
			displayMgr.updateLocation(results[0].geometry.location.lat(), results[0].geometry.location.lng());
			
		} else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
			param = null;
		} else if (status == google.maps.GeocoderStatus.REQUEST_DENIED) {
			param = null;
		} else {
			param = null;
		}
		if (param == null) {
			param = "&parameters[store_address]=" + address;
		}
		displayMgr.updateParamAddress(param);
		displayMgr.lookupAddress();
		displayMgr.displayAddress(zoom,address,boundingBox);
		if (jQuery('#source')) {
			if (jQuery('#source').val() == "store-page-itinerary") {
				showItinerary(jQuery('#latitude').val(),jQuery('#longitude').val(),jQuery('#name').val(),jQuery('#adress').val().replace(/'/g, '&rsquo;').replace(/"/g, '&quot;'),jQuery('#zipcode').val(),jQuery('#city').val().replace(/'/g, '&rsquo;').replace(/"/g, '&quot;'),jQuery('#contact_phone').val(),jQuery('#clean_url').val());
				jQuery('#div-source-itinerary').remove();
			}
		}
	});


	
}

function calcItinerary(lat,lng,start_adress,name) {
	if (displayMgr != null) {
		if (jQuery("#" + start_adress).val() != '' && jQuery("#" + start_adress).val() != Drupal.t('Starting address')){
			displayMgr.calcRoute(lat,lng,jQuery("#" + start_adress).val(),name);
		} else {
			jQuery('div#storelocator-results #results-error').empty();
			jQuery('div#storelocator-results #results-error').append(Drupal.t('Enter a starting address'));
			jQuery('div#storelocator-results #results-error').removeClass('hidden');
		}
	}
}
function showItinerary(lat, lng, name, address, zipcode, city, contact_phone, clean_url) {
	displayMgr.showItineraryDisplay(lat, lng, name, address, zipcode, city, contact_phone, clean_url);
}

//Attach the store as favorite and save the store values in Cookie
function attachStore(store_id, store_name, code_anabel_store, typology_name) {
	var current_loc = window.location.pathname;
	var url_val = window.location.href;
  var is_user_logged_in = Drupal.settings.storelocator_app.is_authenticated_user; 
    if (store_id && store_name && code_anabel_store && typology_name) {
        jQuery.ajax({
            type: 'POST',
            data: {'store_id' : store_id, 'store_name' : store_name,'anabel_code' : code_anabel_store, 'typology_name' : typology_name},
            dataTypeString: 'text',
            url: '/set_favorite_store',
            success: function (data, textStatus, jqXHR) {
            	if (data == 1) {
                    var store_cookie = new Array(store_id, store_name, code_anabel_store, typology_name);
                    var store_cookie_json = JSON.stringify(store_cookie);
                    var cookie_domain = '';
                    if (Drupal.settings.cookie_domain) {
                    	cookie_domain = Drupal.settings.cookie_domain;
                    }
                    if(is_user_logged_in == false){
                     jQuery.cookie("storeval", store_cookie_json, {expires: 21, path  : "/", domain: cookie_domain});
                    }
                    if (typeof(Drupal.removeLocalStorageData) === "function") { 
                      Drupal.removeLocalStorageData('fr_homepage-fr_header_mystore');
                      Drupal.removeLocalStorageData('fr_homepage-fr_header_logo');
                      Drupal.removeLocalStorageData('default');
                      Drupal.removeLocalStorageData('defaultlogo');
                    }
                }
            	else { }
            	window.location.href = current_loc;
            },
            error: function (jqXHR, textStatus, errorThrown) { }
        });
    }
}
function addFilters(checkboxe, type) {
	displayMgr.updateFilterCheckBox(checkboxe, true, type);
}

function getObjectSize(object) {
	  var count=0;
	  for (var key in object)
	    count++;
	  return count;
}
	
function getMap(mapDivID) {
	var serviceURL = Drupal.settings.storelocator_app.storelocator_ws_url + '/stores/js-api/store.json';
	
	if (Drupal.settings.storelocator_app.storelocator_show_map == 1) {

		storeDetailURL = Drupal.settings.storelocator_app.storelocator_local_url + '/'+Drupal.t('store')+'/';
		
		var displayDefault = false;
		var minCluster = Drupal.settings.storelocator_app.storelocator_mincluster;
		var j = 0;
		var services = {};
		var types = {};
		var zoom = null;
		var language= getLang();
		titleSearch = Drupal.t('Your search', language);
		titleDirection= Drupal.t('Get directions', language);
		titleItinerary= Drupal.t('Driving direction to', language);
		libAddr = Drupal.t('Enter a zip code or a city', language);
		address = jQuery('#' + controls.geocoder.address).val();
		if ( address == null || address=="" || address ==libAddr) {
			address = Drupal.settings.storelocator_app.storelocator_default_address;
			zoom = parseInt(Drupal.settings.storelocator_app.storelocator_zoom);
		}
		jQuery('input[id*="edit-services-"]').each(function(i,val) {
			if (val.checked) {	
				services[val.value]=1;
			}
		});
		jQuery('input[id*="edit-typology-"]').each(function(i,val) {
			if (val.checked) {	
				types[val.value]=1;
			} 
		});

		displayMgr = new DisplayManager(Drupal.settings.storelocator_app.storelocator_default_address,Drupal.settings.storelocator_app.storelocator_country_code,language,zoom,serviceURL, storeDetailURL, minCluster, controls, services, types, mapDivID , Drupal.settings.storelocator_app.storelocator_map_channel);
		showAddress(zoom,address + " , " + Drupal.settings.storelocator_app.storelocator_default_address);
	} else{
		var map_url ='';
		if (Drupal.settings.storelocator_app.storelocator_default_map != '') {
			map_url= Drupal.settings.storelocator_app.storelocator_local_url 
			+ '/' + Drupal.settings.storelocator_app.storelocator_module_app_url 
			+ '/images/' + Drupal.settings.storelocator_app.storelocator_default_map;
		}
		if (map_url != '') {
			var html_map = '<img src="'+map_url+'"/>'
			jQuery('#' + mapDivID).append(html_map);
		}
		
	}

	
}

function getLang() {
	var language= Drupal.settings.storelocator_app.storelocator_user_language;
	if (language == null) {
		language = Drupal.settings.storelocator_app.storelocator_language;
	}
	return language;
}

function addServices(box) {
    // Build the URL to reach the WS with the params          
    var wsURL = Drupal.settings.storelocator_app.storelocator_ws_url;    
    wsURL += 'stores/js-api/store.json';
    wsURL += '?parameters[store_service_list]=';
    var storeapi = {
    	    'apiPath': Drupal.settings.storelocator_app.storelocator_ws_url + 'stores/js-api/store.json'
    };
    
    storeapi.retrieve_byservicelist = function(queryUrl, callback) {
    	jQuery.ajax({
	      type: "GET",
	      url: queryUrl,
	      dataType: 'json',
	      success: callback
	    });
	}; 

	var j = 0;
	if (box) {
		jQuery('input[id*="edit-services-"]').each(function(i,val) {
			if (val.checked) {
				if (j > 0) {
					wsURL += ",";
				}
				j++;
				wsURL += val.value;
			} else {
				//
			}
		});
		
		storeapi.retrieve_bytypology = function(queryUrl, callback) {
		    $.ajax({
		      type: "GET",
		      url: queryUrl,
		      dataType: 'json',
		      success: callback
		    });
		}; 
			  
		storeapi.retrieve_byservicelist(wsURL, function(result){
	      if (result == null){
	        var message =  Drupal.t('No stores in this area');
	        var messageHTML = '<span class="storelocator-warning">' + message + '</span>';
	        //Drupal.messages.set(message);
	        jQuery('form#storelocator-app-page-form-service .form-item-store').append(message);
	        jQuery('form#storelocator-app-page-form-service .form-item-store select option[value!="-1"]').remove();
	      } else {
	    	jQuery('form#storelocator-app-page-form-service span.storelocator-warning').remove();
	    	jQuery('form#storelocator-app-page-form-service .form-item-store select option[value!="-1"]').remove();
	
	        // WS result callback : loop on each result to build store select list
	    	jQuery.each(result, function(){
	          var store = jQuery(this)[0];
	          var option = '<option value="' + store.store_id + '">' + store.name + '</option>';
	          
	          jQuery('form#storelocator-app-page-form-service .form-item-store select').append(option);
	    	});
	      }
	    });
	}
} 

function formatDateFilter(date, format) {
	
	if ( date != "") {
		var tab = date.split("/");
		if (format == "dd/mm/yyyy"){
			return date;
		} else {
			alert(Drupal.t('The date format is invalid. please enter this a date with the given format : JJ/MM/AAAA'));
		}
	} else
		return null;
	
}

function checkDate(date,format){
	var tab = date.split("/");
	var aD, dD, dM, dY, s, dYDigit;	
		
	if (format == "dd/mm/yyyy"){
		dD = tab[0];	
		dM = tab[1] - 1;
		dY = tab[2];
	} else {
		alert(Drupal.t('The date format is invalid. please enter this a date with the given format : JJ/MM/AAAA'));
		 return false;
	}

	  s = dY + "";
	  dYDigit = s.length;
	  if (isNaN(dD) || isNaN(dM) || isNaN(dY) || (dY < 1) || (dD < 1) || (dM < 0) || (dM > 11) || (dYDigit != 4) || (dD > DaysIn(dM, dY))){
		  alert(Drupal.t('The date format is invalid. please enter this a date with the given format : JJ/MM/AAAA'));

		  return false;
	  } else{
	   if (dM == 1) {
	    if (!IsLeap(dY) && dD == 29) {
	    	alert(Drupal.t('The date format is invalid. please enter this a date with the given format : JJ/MM/AAAA'));	    	 
	     return false;
	    } else {
	     return true;
	    }
	   } else {
	    return true;
	   }
	  }
	
}

// Methode pour connaitre le nombre de jours dans un mois
function DaysIn ( inMONTH, inYEAR )
{
 var m = 0;
 if (("§0§§2§§4§§6§§7§§9§§11§").indexOf("§" + inMONTH + "§") >= 0) {
	 m = 31;
 } else if (("§3§§5§§8§§10§").indexOf("§" + inMONTH + "§") >= 0) {
	 m = 30;
 } else {
  if (this.IsLeap(inYEAR)) {
	  m = 29;
  } else {
	  m = 28;
  }
 }
 return m;
}
// Methode de verification annee bissextile
 function IsLeap ( inYEAR )
{
 if (inYEAR % 400 == 0) {
  return true;
 } else if ((inYEAR % 4 == 0) && (inYEAR % 100 != 0)){
  return true;
 } else {
  return false;
 }
}

jQuery(function($) {		
		$.datepicker.setDefaults($.datepicker.regional[getLang()]); 
		$('#storelocator-calendar').datepicker();
		$( '#storelocator-calendar').datepicker( "option", "showOtherMonths", true );
		$('.page-store form #filter-advanced-search-box .form-item-special-opening input').attr("disabled","disabled");

}); 

(function ($) {
	
  var storeapi = {};	
  storeapi.retrieve_byarea = function(queryUrl, params, callback) {
	  $.ajax({
	      type: "POST",
	      data: {query : params},
	      url: queryUrl,
	      dataType: 'html',
	      success: callback
	  });
  }; 
  
  

  Drupal.behaviors.storeLocatorFormPage = {
	  attach : function(context){

		  // Ensure the body class fits the css selectors
		  $('body').addClass('page-store');	  
		  
      // Load map in the target canvas	
		  getMap('store-form-map-canvas');
      
      // Initialize autocomplete
      var input = document.getElementById('edit-address');
      var options = {
        types: ['(cities)'], // only displays cities
        componentRestrictions: {country: 'fr'} // limit search on France
      };
      var autocomplete = new google.maps.places.Autocomplete(input, options);
 
		  // Disable store select list
		  $('.page-store form#storelocator-app-block-filter-area-form .form-item-store select').attr("disabled","disabled");
			
		  // Bind the store list building (via WS) on select change event
		  $('.page-store form#storelocator-app-block-filter-area-form .form-item-area').change(function(){
			  $('.page-store form#storelocator-app-block-filter-area-form .form-item-store select').attr("disabled","disabled");	
			  var area = $(this).children('select').val();
		
		      // Build the URL to reach the WS with the params          
		      //var wsURL = Drupal.settings.storelocator_app.storelocator_local_url;    
		      //wsURL += '/store/areas/';
		      
		      // Build the URL to reach the WS with the params          
		      //var params = 'area=' + area;
	
		      // Call the WS
		      //storeapi.retrieve_byarea(wsURL, params, function(result){
		      var mapStore = Drupal.settings.storelocator_app.storelocator_store_list;
		      if (mapStore == null){
		          var message =  Drupal.t('No stores in this area');
		          var messageHTML = '<span class="storelocator-warning">' + message + '</span>';
		          $('form#storelocator-app-block-filter-area-form .form-item-store').append(message);
		          $('form#storelocator-app-block-filter-area-form .form-item-store select option[value!="-1"]').remove();
		      } else {
		          $('form span.storelocator-warning').remove();
		          var htmlSelect = '<select id="edit-store" name="store" class="form-select">';
		          htmlSelect += "<option value='-1'>"+Drupal.t('-- Select the store --')+"</option>";
		          var test = mapStore[area];
		          if (mapStore[area]) {
		        	  $.each(mapStore[area], function(){
		        		  var store = $(this)[0];
				            htmlSelect += '<option value="' + store.clean_url + '">' + store.name + '</option>';
				      });
		          }
			            
		          htmlSelect += "</select>";
		          $('select#edit-store').replaceWith(htmlSelect);
		          $('form#storelocator-app-block-filter-area-form .form-item-store select').removeAttr('disabled');
		        }
		  });
          	  
		  // Bind submit behavior on the link
		  $('.page-store form#storelocator-app-block-filter-area-form a#storelocator-submit-info').click(function(){

		      var choiceValue = $('form#storelocator-app-block-filter-area-form .form-item-store select option:selected').val();
		      
		      if (choiceValue != -1){
			    var currentPath = window.location.pathname;
			    if (currentPath.charAt(currentPath.length - 1) === '/') {
			      currentPath = currentPath + choiceValue;
			    } else {
			      currentPath = currentPath + '/' + choiceValue;
			    }

			    window.location.replace(currentPath);
		      } else {
		    	  var message = Drupal.t('You must select a store first');
		    	  alert(message);
		      }
		      return false;
		  });
	  

		  // Bind store loading on typology list change
		  $('.page-store-typology form#storelocator-app-page-form-typology--2 .form-item-typology').change(function(){
		      
			  var typology = $(this).children('select').val();

		      // Build the URL to reach the WS with the params          
		      var wsURL = Drupal.settings.storelocator_app.storelocator_ws_url;    
		      wsURL += 'stores/js-api/store.json';
		      wsURL += '?parameters[typology]=' + typology;

		      // Call the WS
		      storeapi.retrieve_bytypology(wsURL, function(result){
		        if (result == null){
		          var message =  Drupal.t('No stores in this area');
		          var messageHTML = '<span class="storelocator-warning">' + message + '</span>';
		          //Drupal.messages.set(message);
		          $('form#storelocator-app-page-form-typology--2 .form-item-store').append(message);
		          $('form#storelocator-app-page-form-typology--2 .form-item-store select option[value!="-1"]').remove();
		        } else {
		          $('form#storelocator-app-page-form-typology--2 span.storelocator-warning').remove();
		          $('form#storelocator-app-page-form-typology--2 .form-item-store select option[value!="-1"]').remove();

		          // WS result callback : loop on each result to build store select list
		          $.each(result, function(){
		            var store = $(this)[0];
		            var option = '<option value="' + store.store_id + '">' + store.name + '</option>'
		            $('form#storelocator-app-page-form-typology--2 .form-item-store select').append(option);
		          });
		        }
		      });
		  });
		  
		  $('.page-store form .filter-advanced-search a').click(function(){
			  $(this).toggleClass("active");
			  $("#filter-advanced-search-box").slideToggle("slow"); 
			  return false;
		  });
		  
		  $('#block-filter-opening .form-item-special-opening input').attr("disabled",true);
		  
		  $('#block-filter-opening #storelocator-calendar').change(function(){			  
			  var format = 'dd/mm/yyyy';//$( '#block-filter-opening #storelocator-calendar' ).datepicker( "option", "dateFormat" );
			  var selectedDate = $('#block-filter-opening #storelocator-calendar').val();
			  
			  if (selectedDate != "" ) {
				  
				  if (checkDate(selectedDate,format)) {		  
					  $('#block-filter-opening .form-item-special-opening input').attr("disabled",false);
					  $('#block-filter-opening .form-item-special-opening input').attr('checked', true);
					  $('#block-filter-opening .form-item-open-sunday input').attr('checked', false);
					  $('#block-filter-opening .form-item-open-now input').attr('checked', false);
				  } else {
					  $(this).attr("value", "");
					  $('#block-filter-opening .form-item-special-opening input').attr("disabled",true); 
					  $('#block-filter-opening .form-item-special-opening input').attr('checked', false);
					  if ($('#block-filter-opening #storelocator-calendar').hasClass("cal-def-value")) {
						  $('#block-filter-opening #storelocator-calendar').removeClass("cal-def-value");
					  }
				  }
			  
			  } else {
				  $('#block-filter-opening .form-item-special-opening input').attr("disabled",true); 
				  $('#block-filter-opening .form-item-special-opening input').attr('checked', false);
			  }
			  $('#block-filter-opening #datepicker').attr("value",formatDateFilter(selectedDate, format));
			  displayMgr.updateFilterSpecialDate();
			  
		  });
		  		  
		  $('#block-filter-opening .form-item-special-opening input').click(function() { 
			  if ($('#block-filter-opening .form-item-special-opening input').is(':checked') ) {
				  var format = 'dd/mm/yyyy';//$( '#block-filter-opening #storelocator-calendar' ).datepicker( "option", "dateFormat" );
				  var selectedDate = $('#block-filter-opening #storelocator-calendar').val();
				  $('#block-filter-opening #datepicker').attr("value",formatDateFilter(selectedDate, format));
				  $('#block-filter-opening .form-item-open-sunday input').attr('checked', false);
				  $('#block-filter-opening .form-item-open-now input').attr('checked', false);
			  } else {
				  $('#block-filter-opening .form-item-special-opening input').attr("disabled",true);  	
				  $('#block-filter-opening #storelocator-calendar').attr("value", "");
				  $('#block-filter-opening #datepicker').attr("value", ""); 
				  if ($('#block-filter-opening #storelocator-calendar').hasClass("cal-def-value")) {
					  $('#block-filter-opening #storelocator-calendar').removeClass("cal-def-value");
				  }
			  }
			});	  
		  
		  $('#block-filter-opening .form-item-open-now input').click(function() { 
			  if ($('#block-filter-opening .form-item-open-now input').is(':checked') ) {
				  $('#block-filter-opening .form-item-open-sunday input').attr('checked', false);
				  $('#block-filter-opening .form-item-special-opening input').attr('checked', false);
				  $('#block-filter-opening .form-item-special-opening input').attr("disabled",true);
				  $('#block-filter-opening #storelocator-calendar').attr("value", ""); 
				  $('#block-filter-opening #datepicker').attr("value", ""); 
				  if ($('#block-filter-opening #storelocator-calendar').hasClass("cal-def-value")) {
					  $('#block-filter-opening #storelocator-calendar').removeClass("cal-def-value");
				  }
			  }
		  });	
		  $('#block-filter-opening .form-item-open-sunday input').click(function() { 
			  if ($('#block-filter-opening .form-item-open-sunday  input').is(':checked') ) {
				  $('#block-filter-opening .form-item-open-now input').attr('checked', false);
				  $('#block-filter-opening .form-item-special-opening input').attr('checked', false);
				  $('#block-filter-opening .form-item-special-opening input').attr("disabled",true);
				  $('#block-filter-opening #storelocator-calendar').attr("value", ""); 
				  $('#block-filter-opening #datepicker').attr("value", ""); 
				  if ($('#block-filter-opening #storelocator-calendar').hasClass("cal-def-value")) {
					  $('#block-filter-opening #storelocator-calendar').removeClass("cal-def-value");
				  }
			  }
		  });
		  //Default value 'JJ/MM/AAA' for the calendar
		  $('#block-filter-opening #storelocator-calendar').click(function() { 
			  $('#block-filter-opening #storelocator-calendar').addClass("cal-def-value");
		  });
		  $('#storelocator-app-block-filter-form-opening').keypress(function(e){
			  if ( e.which == 13 ) {
				  e.preventDefault();			  
			  }
		  });
		  
		$('.delete-attached-store-link').live("click", function() {
			var current_loc = window.location.pathname;
		    $.ajax({
		        type: 'POST',
		        data: {'store_id' : $(this).attr('id')},
		        dataTypeString: 'text',
		        url: '/store/favorite_store_delete',
		        success: function (data, textStatus, jqXHR) {
		          // If response is '1', that means that all went well:
		          if (data) {
                    if (typeof(Drupal.removeLocalStorageData) === "function") { 
		      	      Drupal.removeLocalStorageData('fr_homepage-fr_header_mystore');
		      	      Drupal.removeLocalStorageData('fr_homepage-fr_header_logo');
		              Drupal.removeLocalStorageData('default');
		              Drupal.removeLocalStorageData('defaultlogo');
	                  if (Drupal.settings.cookie_domain) {
	                  	cookie_domain = Drupal.settings.cookie_domain;
	                  }
		              jQuery.cookie("storeval", null, {path  : "/", domain: cookie_domain});
		      	    }
                    window.location.href = current_loc;
		          }
		          // Otherwise, that means that an error occured:
		          else {
		            //callback_function(false);
		          }
		        },
		        error: function (jqXHR, textStatus, errorThrown) {
		          //callback_function(false);
		        }
		      });    
		      return true;
		}); 
		/*$(window).ready(function() {	    	
	    	var store_itenary_cookie = getStoreBrowserCookie('store_itenary_cookie');
	    	var itenary_class = "." + store_itenary_cookie;
	    	console.log("++++" + itenary_class);
	    	console.log("*******" + store_itenary_cookie);
	    	if($(itenary_class).length) {
	    		console.log("Class Found ...");
	    	}
	    	else {
	    		console.log("Class Not Found ...");
	    	}
	    	if (store_itenary_cookie != '') {
	    	  console.log(" ==== Its in IF - Start =====");
	    	  $(itenary_class).trigger("click");
	    	  setStoreBrowserCookie('store_itenary_cookie', '');
	    	  console.log(" ==== Its in IF - End =====");
	    	  
	    	}
	    	else {
	    		console.log(" ==== Its in Else =====");
	    		$(itenary_class).trigger( "click" );
		    	setStoreBrowserCookie('store_itenary_cookie', '');
	    	}
	    });*/
		
		/*window.onload = function() {
			var store_itenary_cookie = getStoreBrowserCookie('store_itenary_cookie');
	    	var itenary_class = "." + store_itenary_cookie;
	    		    	
	    	if (store_itenary_cookie != '') {
	    		// If browser is IE set interval
	    		if($.browser.msie) {
	    	 // setInterval(function(){console.log("1111111")}, 300000000000);	    	  
	    	  setTimeout(function() {
	    	      // Do something after 3 seconds
	    		  if($(itenary_class).length) {
    				 $(itenary_class).trigger("click");
	 		    	 //setStoreBrowserCookie('store_itenary_cookie', '');
	 		  	   }
	    	     }, 3000);
	    		}
	    		else {
    			  if($(itenary_class).length) {
    				 $(itenary_class).trigger("click");
	 		    	  //setStoreBrowserCookie('store_itenary_cookie', '');
 		  	      }   
	    		}
	    	}
		};*/
	  }
  };
		
	  

}(jQuery));
/**
 * Get Cookie
 * @param cname
 */
function getStoreBrowserCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i=0; i<ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1);
      if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
  }
  return "";
}

//Set the itenary cookie
function setStoreBrowserCookie(cname, cvalue, exdays) {
	  var d = new Date();
	  d.setTime(d.getTime() + (exdays*24*60*60*1000));
	  var expires = "expires="+d.toUTCString();
	  document.cookie = cname + "=" + cvalue + "; " + expires + ";path=/";;
}