var SECURE_URL = "http://" + document.domain + ":" + location.port + "/";
var SSL_SECURE_URL = "https://" + document.domain + ":" + location.port + "/";


function setupGlobalSearch()
{
    $("#btn_global_search").click(function() {
		var searchkeyword = $("#global_search").val();
		if(searchkeyword != '')
		{
	        window.location = "/Other/Search.aspx?search=" + $("#global_search").val();
		}
    });
    
   $("#global_search").unbind("keyup").focus(function() {
        $(this).keyup(function(e) {	        

	        if(e.keyCode == 13) {
				{ 
				
				$("#global_search").val($.trim($("#global_search").val()));
				var searchkeyword = $.trim($("#global_search").val());
				if(searchkeyword != '')
					{
					 window.location = "/Other/Search.aspx?search=" + $("#global_search").val();				 
					 $("#btn_global_search").click();
					}
					
					event.returnValue=false;
				event.cancel = true;
				}
	        }
        });
		
    });


	$("#global_search").unbind("keypress").focus(function() {
        $(this).keypress(function(e) {	        
			
	        if(e.keyCode == 13) {
				{ 

				 var searchkeyword = $.trim($("#global_search").val());
					if(searchkeyword != '')
					{
					 window.location = "/Other/Search.aspx?search=" + $("#global_search").val();
					 $("#btn_global_search").click();
					 }

					 				 event.returnValue=false;
				 event.cancel = true;

				}


	        }
        });
		
    });

	
}



function setupLogoff()
{
    $("#header .member_logged_in a").click(function() {
        var url_value;
        if(document.URL.indexOf("https")!= -1)
         {   url_value=SSL_SECURE_URL;}
            else{
            url_value=SECURE_URL;}
            
        $.ajax(
		{
		    url:url_value + "json.ashx",
		    cache:false,
		    data:{method:'Logout'},					
		    dataType:"json",
		    type:"POST",
		    success:function(response){
			    if (response.results.success)
			    {
			        window.location = "/";
			    }
			   		
		    },
		    error:function(XMLHttpRequest, textStatus, errorThrown)
		    {
			    
		    }				
	    });
	    
        return false;
    });
}


/* login */
function showLogin(){  
    
	$('#header #toolbar ul li ul li.member_login a').addClass('active');
	$('#header #toolbar ul li ul li.member_login .form input').each(function() {
	    $(this).bind("focus",function() {
	        this.value = '';
	    });
	});
	$('#header #toolbar ul li ul li.member_login ul li.showLoginContainer').animate({width: "230px"}, 750, "swing", function(){
		$("#txtToolLoginUsername").val('email');
		$("#txtToolLoginPass").val('password');
		$('#header #toolbar ul li ul li.member_login .showLoginContainer').hide();
		$('#header #toolbar ul li ul li.member_login .form').show();
	});
	
	$("#header #btnLoginSubmit").click(function () {
	    var username = $("#txtToolLoginUsername").val();
        var password = $("#txtToolLoginPass").val();
        
	var url_value;
        if(document.URL.indexOf("https")!= -1)
         {   url_value=SSL_SECURE_URL;}
            else{
            url_value=SECURE_URL;}

        $.ajax(
		{
		    url:url_value + "json.ashx",
		    cache:false,
		    data:{method:'Login', user:username, pass:password},					
		    dataType:"json",
		    type:"POST",
		    success:function(response){
			    
			    if (response.results.success)
			    {
					// location.reload(true);
					window.location = "/iCrunch.aspx";
			    }
			    else
			    {
			       //TODO: login failed 			      
				   window.location = "/iCrunch Login.aspx?ErrCode=1";
				    alert("Invalid username / password");
			    }				
		    },
		    error:function(XMLHttpRequest, textStatus, errorThrown)
		    {
			   //  alert("Could not login: " +  textStatus + ":" + errorThrown); // TODO: add a better message for this.
				//	 window.location = "/iCrunch Login.aspx?ErrCode=1";
		    }				
	    });
	    
	    return false;
	});


	   $("#txtToolLoginPass").unbind("keyup").focus(function() {
        $(this).keyup(function(e) {	        

	        if(e.keyCode == 13) {
				{				
					 $("#header #btnLoginSubmit").click();
				}					
					event.returnValue=false;
					event.cancel = true;
				}
	        })
	   });


		  $("#txtToolLoginPass").unbind("keypress").focus(function() {
        $(this).keypress(function(e) {	        

	        if(e.keyCode == 13) {
				{				
					 $("#header #btnLoginSubmit").click();
				}					
					event.returnValue=false;
					event.cancel = true;
				}
	        })
        });
}

/* For the right column search gadget */
function setupSearchGadget()
{

    $("#txtSearchBox_Gadget").bind("focus", function(e)
    {
        $("#txtSearchBox_Gadget").attr("value","");
    });
    
    $("#btn_search").bind("click", function(e)
    {
        e.stopPropagation();
        e.preventDefault();
        var zip = $("#txtSearchBox_Gadget").attr("value");
        document.location.href = "/Locations/Find%20a%20Location.aspx?zip=" + zip;
        
    });
}

function setupSearchGadgetFranchise(dest) {

    $("#txtSearchBox_Gadget").bind("focus", function(e) {
        $("#txtSearchBox_Gadget").attr("value", "");
    });

    $("#btn_search").bind("click", function(e) {
        e.stopPropagation();
        e.preventDefault();
        var zip = $("#txtSearchBox_Gadget").attr("value");
        //alert(dest);
        document.location.href = dest + "?zip=" + zip;

    });
}

/* flash media popup */
function popupFlashMedia( itemId, fromFlash, types  ){
	var title = '';
	var itemPath = '';
	if (itemId != null && itemId != '')
	{
	    itemId = itemId.replace(/{/, '');
	    itemId = itemId.replace(/}/, '');
	    
	    itemPath = 'itemId=' + itemId;
	    if (fromFlash == "1")
	    {
	        itemPath += '&fromFlash=' + fromFlash;
	    }
	}

	var URL = '/layouts/Crunch/Popups/FlashPopupContent.aspx?'+ itemPath + '&mediatype=' + types;
    
	var settings = "toolbar=0,status=0,scrollbars=0";
	
	URL = URL + '&KeepThis=true&TB_iframe=true&height=446&width=655&modal=true';
	
	tb_show( title, URL, settings);
}

/* flash media auto play on load */
function AutoPlayMedia(){
	var title = '';
	var itemPath = '';
	var fromFlash = '';

	var itemId = getQSParameterByName('media');
	var types = getQSParameterByName('mediatype');

	if (itemId != null && itemId != '' && types !='')
	{
	    itemId = itemId.replace(/{/, '');
	    itemId = itemId.replace(/}/, '');
	    
	    itemPath = 'itemId=' + itemId;
	    if (fromFlash == "1")
	    {
	        itemPath += '&fromFlash=' + fromFlash;
	    }
	

	var URL = '/layouts/Crunch/Popups/FlashPopupContent.aspx?'+ itemPath + '&mediatype=' + types;
    
	var settings = "toolbar=0,status=0,scrollbars=0";
	
	URL = URL + '&KeepThis=true&TB_iframe=true&height=446&width=655&modal=true';
	
	tb_show( title, URL, settings);
	
	}

	return false;
}


function getQSParameterByName( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function popupMediaContent(url, itemId, fromFlash, types  ){
	var title = '';
	var itemPath = '';
	if (itemId != null && itemId != '')
	{
	    itemId = itemId.replace(/{/, '');
	    itemId = itemId.replace(/}/, '');
	    
	    itemPath = 'itemId=' + itemId;
	    if (fromFlash == "1")
	    {
	        itemPath += '&fromFlash=' + fromFlash;
	    }
	}

	var URL = url + '.aspx?'+ itemPath + '&mediatype=' + types ; 
    
	var settings = "toolbar=0,status=0,scrollbars=0";
	
	URL = URL + '&KeepThis=true&TB_iframe=true&height=446&width=655&modal=true';
	
	tb_show( title, URL, settings);
}

/* popup training inquiry */
function popupTrainingInquiry(type) {
    
    var URL = '/layouts/Crunch/Popups/TrainingInquiry.aspx';
    var title = 'Inquire About Personal Training';
    var settings = "toolbar=0,status=0,scrollbars=0";
    if (type.indexOf(' ') > 0) {
        type = type.substring(0, type.indexOf(' '));
    }
    
	URL = URL + '?type=' + type +'&KeepThis=true&TB_iframe=true&height=600&width=655&modal=true';
	
	tb_show( title, URL, settings);
}

/* Edy: popup x-pert inquiry */
function popupXPertInquiry(type) {
    var URL = '/layouts/Crunch/Popups/XPertInquiry.aspx';
    var title = 'X-Pert Pole Inquiry';
    var settings = "toolbar=0,status=0,scrollbars=0";

    URL = URL + '?type=' + type + '&KeepThis=true&TB_iframe=true&height=600&width=655&modal=true';
    tb_show(title, URL, settings);
}

/* Edy: popup x-pert inquiry for Franchise locations*/
function popupFranchiseXPertInquiry(type) {
    var URL = '/layouts/Franchise/Popups/FranchiseXPertInquiry.aspx';
    var title = 'X-Pert Pole Inquiry';
    var settings = "toolbar=0,status=0,scrollbars=0";

    URL = URL + '?type=' + type + '&KeepThis=true&TB_iframe=true&height=600&width=655&modal=true';
    tb_show(title, URL, settings);
}

/* popup corporate inquiry */
function popupCorporateInquiry() {
    var URL = '/layouts/Crunch/Popups/CorporateInquiry.aspx';
    var title = 'Inquire About Corporate Memberships';
    var settings = "toolbar=0,status=0,scrollbars=0";
	
	URL = URL + '?KeepThis=true&TB_iframe=true&height=600&width=655&modal=true';
	
	tb_show( title, URL, settings);
}

/* popup franchise inquiry */
function popupFranchiseInquiry() {
    var URL = '/layouts/Crunch/Popups/FranchiseInquiry.aspx';
    var title = 'Inquire About Franchise';
    var settings = "toolbar=0,status=0,scrollbars=0";
	
	URL = URL + '?KeepThis=true&TB_iframe=true&height=600&width=655&modal=true';
	
	tb_show( title, URL, settings);
}

/* global popup */
function popupOpen( URL, dimentions, callingUrl ){
	var settings = "toolbar=0,status=0,scrollbars=0";
	var title = "";
	URL = URL + "?";
	
	if (callingUrl != undefined && callingUrl != '')
	{
	    URL = URL + '&gotourl=' + escape(callingUrl);
	}
	
	URL = URL + '&KeepThis=true&TB_iframe=true&' + dimentions + '&modal=true';
	
	tb_show( title, URL, settings);
}

function popupClose( callFlashSlideShowResume ){
	tb_remove();
	if( callFlashSlideShowResume == '1' ){
		document.getElementById('flashHero').resumeSlideShow();
	}
}



/*
 *
 *	jQuery Timer plugin v0.1
 *		Matt Schmidt [http://www.mattptr.net]
 *
 *	Licensed under the BSD License:
 *		http://mattptr.net/license/license.txt
 *
 */
 
 jQuery.timer = function (interval, callback)
 {
 /**
  *
  * timer() provides a cleaner way to handle intervals  
  *
  *	@usage
  * $.timer(interval, callback);
  *
  *
  * @example
  * $.timer(1000, function (timer) {
  * 	alert("hello");
  * 	timer.stop();
  * });
  * @desc Show an alert box after 1 second and stop
  * 
  * @example
  * var second = false;
  *	$.timer(1000, function (timer) {
  *		if (!second) {
  *			alert('First time!');
  *			second = true;
  *			timer.reset(3000);
  *		}
  *		else {
  *			alert('Second time');
  *			timer.stop();
  *		}
  *	});
  * @desc Show an alert box after 1 second and show another after 3 seconds
  *
  * 
  */

	var interval = interval || 100;

	if (!callback)
		return false;
	
	_timer = function (interval, callback) {
		this.stop = function () {
			clearInterval(self.id);
		};
		
		this.internalCallback = function () {
			callback(self);
		};
		
		this.reset = function (val) {
			if (self.id)
				clearInterval(self.id);
			
			var val = val || 100;
			this.id = setInterval(this.internalCallback, val);
		};
		
		this.interval = interval;
		this.id = setInterval(this.internalCallback, this.interval);
		
		var self = this;
	};
	
	return new _timer(interval, callback);
 };
 
 
 /**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

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 = c1 = 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;
    }

}


 /**
 * jQuery.query - Query String Modification and Creation for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2008/05/28
 *
 * @author Blair Mitchelmore
 * @version 2.0.0
 *
 **/
new function(settings) { 
  // Various Settings
  var $separator = settings.separator || '&';
  var $spaces = settings.spaces === false ? false : true;
  var $suffix = settings.suffix === false ? '' : '[]';
  var $prefix = settings.prefix === false ? false : true;
  var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
  
  jQuery.query = new function() {
    var is = function(o, t) {
      return o != undefined && o !== null && (!!t ? o.constructor == t : true);
    };
    var parse = function(path) {
      var m, rx = /\[([^[]*)\]/g, match = /^(\S+?)(\[\S*\])?$/.exec(path), base = match[1], tokens = [];
      while (m = rx.exec(match[2])) tokens.push(m[1]);
      return [base, tokens];
    };
    var set = function(target, tokens, value) {
      var o, token = tokens.shift();
      if (typeof target != 'object') target = null;
      if (token === "") {
        if (!target) target = [];
        if (is(target, Array)) {
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        } else if (is(target, Object)) {
          var i = 0;
          while (target[i++] != null);
          target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
        } else {
          target = [];
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        }
      } else if (token && token.match(/^\s*[0-9]+\s*$/)) {
        var index = parseInt(token, 10);
        if (!target) target = [];
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else if (token) {
        var index = token.replace(/^\s*|\s*$/g, "");
        if (!target) target = {};
        if (is(target, Array)) {
          var temp = {};
          for (var i = 0; i < target.length; ++i) {
            temp[i] = target[i];
          }
          target = temp;
        }
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else {
        return value;
      }
      return target;
    };
    
    var queryObject = function(a) {
      var self = this;
      self.keys = {};
      
      if (a.queryObject) {
        jQuery.each(a.get(), function(key, val) {
          self.SET(key, val);
        });
      } else {
        jQuery.each(arguments, function() {
          var q = "" + this;
          q = q.replace(/^[?#]/,''); // remove any leading ? || #
          q = q.replace(/[;&]$/,''); // remove any trailing & || ;
          if ($spaces) q = q.replace(/[+]/g,' '); // replace +'s with spaces
          
          jQuery.each(q.split(/[&;]/), function(){
            var key = this.split('=')[0];
            var val = this.split('=')[1];
            
            if (!key) return;
            
            if (/^[+-]?[0-9]+\.[0-9]*$/.test(val)) // simple float regex
              val = parseFloat(val);
            else if (/^[+-]?[0-9]+$/.test(val)) // simple int regex
              val = parseInt(val, 10);
            
            val = (!val && val !== 0) ? true : val;
            
            if (val !== false && val !== true && typeof val != 'number')
              val = decodeURIComponent(val);
            
            self.SET(key, val);
          });
        });
      }
      return self;
    };
    
    queryObject.prototype = {
      queryObject: true,
      has: function(key, type) {
        var value = this.get(key);
        return is(value, type);
      },
      GET: function(key) {
        if (!is(key)) return this.keys;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        while (target != null && tokens.length != 0) {
          target = target[tokens.shift()];
        }
        return target || "";
      },
      get: function(key) {
        var target = this.GET(key);
        if (is(target, Object))
          return jQuery.extend(true, {}, target);
        else if (is(target, Array))
          return target.slice(0);
        return target;
      },
      SET: function(key, val) {
        var value = !is(val) ? null : val;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        this.keys[base] = set(target, tokens.slice(0), value);
        return this;
      },
      set: function(key, val) {
        return this.copy().SET(key, val);
      },
      REMOVE: function(key) {
        return this.SET(key, null).COMPACT();
      },
      remove: function(key) {
        return this.copy().REMOVE(key);
      },
      EMPTY: function() {
        var self = this;
        jQuery.each(self.keys, function(key, value) {
          delete self.keys[key];
        });
        return self;
      },
      empty: function() {
        return this.copy().EMPTY();
      },
      copy: function() {
        return new queryObject(this);
      },
      COMPACT: function() {
        function build(orig) {
          var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
          if (typeof orig == 'object') {
            function add(o, key, value) {
              if (is(o, Array))
                o.push(value);
              else
                o[key] = value;
            }
            jQuery.each(orig, function(key, value) {
              if (!is(value)) return true;
              add(obj, key, build(value));
            });
          }
          return obj;
        }
        this.keys = build(this.keys);
        return this;
      },
      compact: function() {
        return this.copy().COMPACT();
      },
      toString: function() {
        var i = 0, queryString = [], chunks = [], self = this;
        var addFields = function(arr, key, value) {
          if (!is(value) || value === false) return;
          var o = [key];
          if (value !== true) {
            o.push("=");
            o.push(encodeURIComponent(value));
          }
          arr.push(o.join(""));
        };
        var build = function(obj, base) {
          var newKey = function(key) {
            return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
          };
          jQuery.each(obj, function(key, value) {
            if (typeof value == 'object') 
              build(value, newKey(key));
            else
              addFields(chunks, newKey(key), value);
          });
        };
        
        build(this.keys);
        
        if (chunks.length > 0) queryString.push($hash);
        queryString.push(chunks.join($separator));
        
        return queryString.join("");
      }
    };
    
    return new queryObject(location.search, location.hash);
  };
}(jQuery.query || {}); // Pass in jQuery.query as settings object

/* containerToggler */
$(document).ready(function() {
	var togglerContainer = '';
	
	// check for toggle containers
	if( $('.togglerContainer').size() != 0 ){
		//
		$('.togglerContainer').each( function(){
			togglerContainer = $(this);
			$(this).find('.togglerLink').each( function(){
				$(this).click( function(){
					togglerContainer.find('.tContainer').hide();
					togglerContainer.find('#' + $(this).attr('toggleToId')).show();
					if( typeof $(this).attr('toggleImgTo') != 'undefined' ){
						togglerContainer.find('#' + $(this).attr('toggleToId') + ' img').attr('src', $(this).attr('toggleImgTo'));
					}
					return false;
				});
			});
		});
	}
});


function addBorders()
{
    $(".instructorThumbImage").each(function() {
        $(this).after("<div class=\"instructorImageBorder pngFix\"></div>");
    });
   
    $(".eventThumbImage").each(function() {
        $(this).after("<div class=\"eventImageBorder pngFix\"></div>");
    });
    
    $(".eventThumbImageAlt").each(function() {
        $(this).after("<div class=\"eventImageBorderAlt pngFix\"></div>");
    });
    
  
    $(".locationThumbImage").each(function() {
        if ($(".locationImageBorder", $(this).parent()).length == 0)
        {
            $(this).parent().append("<div class=\"locationImageBorder pngFix\"></div>");
        }
    });
    
    
}




$(document).ready(function() {
   var badBrowser = (/MSIE ((5\.5))/.test(navigator.userAgent) && navigator.platform == "Win32");
   
   if (badBrowser) {
     
     
   
   }
   else
   {
        // setupMenu();
         addBorders();
   }
  
	setupLogoff();
	setupGlobalSearch();

});

function ChangeCityRedirection() {
    //alert(document.getElementById('global_search').value);

    var cityVal = document.getElementById('global_search').value;
    if(cityVal != "NONE")
        window.location = "/Pages/SiteGateway.aspx?lid=" + cityVal;
}


