$(document).ready(function() {
    $('.toggleDiv').hide();
    
    $('.cc_amount_wrap input').live('keypress', function(event) {
        // Backspace, tab, enter, end, home, left, right, period
        var controlKeys = [8, 9, 13, 35, 36, 37, 39, 46];
        // IE doesn't support indexOf
        var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
        // Some browsers just don't raise events for control keys. Easy.
        // e.g. Safari backspace.
        if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
            (49 <= event.which && event.which <= 57) || // Always 1 through 9
            (48 == event.which && $(this).attr("value")) || // No 0 first digit
            isControlKey) // Opera assigns values for control keys.
        {
            if (event.which == 46) //period key code
            {
                if ($(this).val().indexOf(".") >= 0) {
                    event.preventDefault();
                }
                else if ($(this).val() == "") {
                    $(this).val("0");
                }
            }
            return;
        } else {
            event.preventDefault();
        }
    });

    $('.cc_submit').live('click', function() {
        $.ajax({
            type: "POST",
            url: "/WebServices/CurrencyConverter.asmx/GetCurrency",
            data: "{'amount':'" + $(this).parent('.cc_button').parent('.cc_calculator_inner').children('.cc_amount_wrap').children('input').val() +
                "', 'fromCurrency':'" + $(this).parent('.cc_button').parent('.cc_calculator_inner').children('.cc_from_wrap').children('select').val() +
                "', 'toCurrency':'" + $(this).parent('.cc_button').parent('.cc_calculator_inner').children('.cc_to_wrap').children('select').val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function(result) {
                $('.cc_results').css("font-size", "13px");
                $('.cc_results').html("An error has occurred, try again later.");
            },
            success: function(data) {
                $('.cc_results').html(data.d);
            }
        });
    });

    $('.toggleBtn').live('click', function() {
        IEGeneralDesignChanges();

        //Used only when the currency converter is being rendered on the tee times search page
        if ($('.searchRes').length != 0) {
            var str = $(this).parent('.cost').text();
            var pricePerPlayer = (str.match(/.*player/i))[0].replace(" /player", "");
            var price = pricePerPlayer.match(/\d+.\d+/i);
            $('.cc_results').html("");
            $('.toggleDiv').css('left', $(this).offset().left);
            $('.toggleDiv').css('top', $(this).offset().top);
        }

        $('.toggleDiv').hide();
        $('.toggleDiv').toggle('fast');
        return false;
    });

    $('.toggleCloseBtn').live('click', function() {
        $('.toggleDiv').hide();
    });
});

function IEGeneralDesignChanges() {
    if ($.browser.msie) {
        if ($.browser.version == 6) {
            $('.cc_from_wrap').css('margin-left', '30px');
            $('.cc_to_wrap').css('margin-left', '30px');
            $('.cc_results').css('margin-left', '30px');
        }
        if ($.browser.version == 6 || $.browser.version == 7) {
            if (document.documentMode != 8 && document.documentMode != 9) {
                IE7DesignChanges();
            }
        }
        if ($.browser.version >= 8) {
            if (document.documentMode == 7) {
                IE7DesignChanges();
            }
        }
        if ($.browser.version < 8) {
            $('.toggleDiv').css('margin-top', '25px');
            $('.toggleDiv').css('margin-left', '-205px');
        }
    }
}

function IE7DesignChanges() {
    $('.cc_amount_wrap').css('margin-top', '34px');
}

function DisableRemovePromo(buttonID) {
    $('#' + buttonID).attr('disabled', 'disabled');
}
    

// Rollover  v2.0.1
// documentation: http://www.dithered.com/javascript/rollover/index.html
// license: http://creativecommons.org/licenses/by/1.0/


function isDefined(property) {
  return (typeof property != 'undefined');
}

var rolloverInitialized = false;
function rolloverInit() {
   if (!rolloverInitialized && isDefined(document.images)) {
      
      // get all images (including all <input type="image">s)
      // use getElementsByTagName() if supported
      var images = new Array();
      if (isDefined(document.getElementsByTagName)) {
         images = document.getElementsByTagName('img');
         var inputs = document.getElementsByTagName('input');
         for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].type == 'image') {
               images[images.length] = inputs[i];
            }
         }
      }
      
      // otherwise, use document.images and document.forms collections
      // remove if not supporting IE4, Opera 4-5
      else {
         images = document.images;
         inputs = new Array();
         for (var formIndex = 0; formIndex < document.forms.length; formIndex++) {
            for (var elementIndex = 0; elementIndex < document.forms.elements.length; elementIndex++) {
               if (isDefined(document.forms.elements[i].src)) {
                  inputs[inputs.length] = document.forms.elements[i];
               }
            }
         }
      }
      
      // get all images with '_off.' in src value
      for (var i = 0; i < images.length; i++) {
         if (images[i].src.indexOf('_off.') != -1) {
            var image = images[i];
            
            // store the off state filename in a property of the image object
            image.offImage = new Image();
            image.offImage.src = image.src;
            
            // store the on state filename in a property of the image object
            // (also preloads the on state image)
            image.onImage = new Image();
            image.onImage.imageElement = image;
            
            // add onmouseover and onmouseout event handlers once the on state image has loaded
            // Safari's onload is screwed up for off-screen images; temporary fix
            if (navigator.userAgent.toLowerCase().indexOf('safari') != - 1) {
               image.onmouseover = function() {
                  this.src = this.onImage.src;
               };
               image.onmouseout = function() {
                  this.src = this.offImage.src;
               };
            }
            else {
               image.onImage.onload = function() {
                  this.imageElement.onmouseover = function() {
                     this.src = this.onImage.src;
                  };
                  this.imageElement.onmouseout = function() {
                     this.src = this.offImage.src;
                  };
               };
            }
            
            // set src of on state image after defining onload event handler
            // so cached images (that load instantly in IE) will trigger onload
            image.onImage.src = image.src.replace(/_off\./, '_on.');
         }
      }
   }
   rolloverInitialized = true;
}

// call rolloverInit when document finishes loading
if (isDefined(window.addEventListener)) {
   window.addEventListener('load', rolloverInit, false);
}
else if (isDefined(window.attachEvent)) {
   window.attachEvent('onload', rolloverInit);
}

// Window opener functions  v1.0.6
// http://www.dithered.com/javascript/window/index.html

/*******************************************************************************
	Popup Window openers
*******************************************************************************/

var winReference = null;


// Open a window at a given position on the screen
function openPositionedWindow(url, name, width, height, x, y, status, scrollbars, moreProperties, openerName) {
	
	// ie 4.5 and 5.0 mac - windows are 2 pixels too short; if a statusbar is used, the window will be an additional 15 pixels short
	var agent = navigator.userAgent.toLowerCase();
	if (agent.indexOf("mac") != -1 && agent.indexOf("msie") != -1 && (agent.indexOf("msie 4") != -1 || agent.indexOf("msie 5.0") != -1) ) {
		height += (status) ? 17 : 2;
	}

	// Adjust width if scrollbars are used (pc places scrollbars inside the content area; mac outside) 
	width += (scrollbars != '' && scrollbars != null && agent.indexOf("mac") == -1) ? 16 : 0;

	var properties = 'width=' + width + ',height=' + height + ',screenX=' + x + ',screenY=' + y + ',left=' + x + ',top=' + y + ((status) ? ',status' : '') + ',scrollbars=' + ((scrollbars) ? '' : '=no') + ((moreProperties) ? ',' + moreProperties : '');
	var reference = openWindow(url, name, properties, openerName);
	
	return reference;
}


// Open a window at the center of the screen
function openCenteredWindow(url, name, width, height, status, scrollbars, moreProperties, openerName) {
	var x, y = 0;
	if (screen) {
      x = (screen.availWidth - width) / 2;
	   y = (screen.availHeight - height) / 2;
   }
	if (!status) status = '';
	if (!openerName) openerName = '';
	var reference = openPositionedWindow(url, name, width, height, x, y, status, scrollbars, moreProperties, openerName);
	return reference;
}	

function openCW(url, name, width, height, status, scrollbars, moreProperties, openerName) {
  openCenteredWindow(url, name, width, height, status, scrollbars, moreProperties, openerName) 
}

// Open a window at the center of the parent window
function openCenteredOnOpenerWindow(url, name, width, height, status, scrollbars, moreProperties, openerName) {
	var centerX = 0;
   var centerY = 0;
   if (window.screenX != null && window.outerWidth) {
      centerX = window.screenX + (window.outerWidth / 2);
      centerY = window.screenY + (window.outerHeight / 2);
   }
   else if (window.screenLeft) {
      if (document.documentElement) {
         centerX = window.screenLeft + (document.documentElement.offsetWidth / 2);
         centerY = window.screenTop + (document.documentElement.offsetHeight / 2);
      }
      else if (document.body && document.body.offsetWidth) {
         centerX = window.screenLeft + (document.body.offsetWidth / 2);
         centerY = window.screenTop + (document.body.offsetHeight / 2);
      }
   }
   
   if (centerX == 0) {
      openCenteredWindow(url, name, width, height, status, scrollbars, moreProperties, openerName);
   }
   var x = parseInt(centerX - (width / 2));
   var y = parseInt(centerY - (height / 2));
	if (!status) status = '';
	if (!openerName) openerName = '';
	var reference = openPositionedWindow(url, name, width, height, x, y, status, scrollbars, moreProperties, openerName);
	return reference;
}	


// Open a full-screen window (different from IE's fullscreen option)
function openMaxedWindow(url, name, scrollbars, openerName) {
	var x, y = 0;
	var width  = 600;
	var height = 800;
	if (screen) {
      if (screen.availLeft) {
         x = screen.availLeft;
         y = screen.availTop;
      }
      width  = screen.availWidth - 6;
	   height = screen.availHeight - 29;
   }
	var reference = openPositionedWindow(url, name, width, height, x, y, false, scrollbars, openerName);
	return reference;
}



// Core utility function that actually creates the window and gives focus to it
function openWindow(url, name, properties, openerName) {

	// ie4.x pc can't give focus to windows containing documents from a different domain
	// in this case, initially load a local interstisial page to allow focussing before loading final url
	var agent = navigator.userAgent.toLowerCase();
	if (agent.indexOf("msie") != -1 && parseInt(navigator.appVersion) == 4 && agent.indexOf("msie 5") == -1 && agent.indexOf("msie5") == -1 && agent.indexOf("win") != -1 && url.indexOf('http://') == 0) {
		winReference = window.open('about:blank', name, properties);
		
		setTimeout('if (winReference && !winReference.closed) winReference.location.replace("' + url + '")', 300);
	}
	else {
		winReference = window.open(url, name, properties);
	}

	// ie doesn't like giving focus immediately (to new window in 4.5 on mac; to existing ones in 5 on pc)
	setTimeout('if (winReference && !winReference.closed) winReference.focus()', 200);
	
	if (openerName) self.name = openerName;
	return winReference;
}


function openSizing(url){
	openCenteredWindow(url, 'sizing', 525, 600, 'yes', 'yes');
}

function textCounter( field, maxlimit ) {
  if ( field.value.length > maxlimit ){
    field.value = field.value.substring( 0, maxlimit );
    alert( 'Your message may not exceed 252 characters in length.' );
  }
}

function cdZoom(file,fname,width,height) {
	window.open(file,fname,'toolbar=no,status=no,width='+width+',height='+height+',directories=no,scrollbars=yes,location=no,resizable=yes,menubar=no')
}

function puv2(file,fname,width,height) {
	window.open(file,fname,'toolbar=no,status=no,width='+width+',height='+height+',directories=no,scrollbars=yes,location=no,resizable=yes,menubar=no')
}


function popWin(file,fname,width,height) {
	window.open(file,fname,'toolbar=no,status=no,width='+width+',height='+height+',directories=no,scrollbars=yes,location=no,resizable=yes,menubar=yes')
}

function getElementOffset(elementID, property, relativeElmID) {
   var offset = 0;
   if(typeof elementID == "object")
   {
   var element = elementID;
   }else{
   var element = document.getElementById(elementID);
   }
   if(typeof element == "undefined" || element == null)
   {
    return "NaN";
   }
   var relativeElm = document.getElementById(relativeElmID);

   if(relativeElm == null || typeof relativeElm == "undefined")
      relativeElm = document.body;
   do {
      offset += eval('element.offset' + property);
      element = element.offsetParent;
   } while (element != relativeElm && element != null);
   return parseInt(offset);
}

function showHideZoom(action){
  if(action=="hide"){
    var zoomImageDiv = document.getElementById("zoomImage");
    zoomImageDiv.style.left = '-1000px';
    zoomImageDiv.style.visibility = 'hidden';
  }
  if(action=="show"){

    var zoomImageDiv = document.getElementById("zoomImage");
    var popUpIframe = document.getElementById("popUpImgIframe");

    zoomImageDiv.style.left = getElementOffset('inside', 'Left', 'parentContainer') + "px";
    zoomImageDiv.style.top = (getElementOffset('inside', 'Top', 'parentContainer') + 6) + "px";

    zoomImageDiv.style.visibility = 'visible';
    popUpIframe.style.width = (zoomImageDiv.offsetWidth - 2) + "px";

    /*if(browser.isIE){
      popUpIframe.style.height = (document.frames("popUpImgIframe").document.getElementById("zoomImgFile").height + 5) + "px";
    }else{
      popUpIframe.style.height = (popUpIframe.contentDocument.height - 1) + "px";
    } */

  }
}
/* check for Search box is null before submitting */





// Layer Scripts

	function toggleLayer( whichLayer )
		{  
		var elem, vis;  
		if( document.getElementById )
			elem = document.getElementById( whichLayer ); 
		 else if( document.all ) 
			elem = document.all[whichLayer];  
		else if( document.layers ) 
			elem = document.layers[whichLayer];  
		vis = elem.style; 
		if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
			vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';  
		vis.display = (vis.display==''||vis.display=='block')?'none':'block';}


		// COMMUNITY NAV



		function verifyPricingForm() {
		    var themessage = "You are required to complete the following fields: ";
		    var pattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
		    if (document.forms['PricingForm'].firstName.value == "") {
		        themessage = themessage + " - First Name";
		    }
		    if (document.forms['PricingForm'].lastName.value == "") {
		        themessage = themessage + " -  Last Name";
		    }
		    if (document.forms['PricingForm'].stateProvince.value == "") {
		        themessage = themessage + " -  State/Province";
		    }
		    if (document.forms['PricingForm'].zipPostalCode.value == "") {
		        themessage = themessage + " -  Zip/PostalCode";
		    }
		    if (document.forms['PricingForm'].country.value == "") {
		        themessage = themessage + " -  Country";
		    }
		    if (document.forms['PricingForm'].email.value == "") {
		        themessage = themessage + " -  Email";
		    }
		    if (!pattern.test(document.forms['PricingForm'].email.value)) {
		        themessage = themessage + " -  Invalid Email";
		    }
		    //alert if fields are empty and cancel form submit
		    if (themessage == "You are required to complete the following fields: ") {
		        //document.forms['PricingForm'].submit();
		        return true;
		    }
		    else {
		        alert(themessage);
		        return false;
		    }
		}

