var win = null;

	function ToggleValidation(element, txtElement, className)
	{
		var validationElement = $('advice-' + className + '-' + txtElement);
		if (validationElement)
		{
			if (!Validation.get(className).test(element.value))
			{
				validationElement.show();
				element.removeClassName('validation-passed');
				element.addClassName('validation-failed');
			}
			else
			{
				validationElement.hide();
				element.removeClassName('validation-failed');
				element.addClassName('validation-passed');
			}
		}
	}

    /* This function change the class name of the text element for proper validation. */
	function ChangePostalZipClass(txtElement, value)
	{
		// NOTE:
		// Assuming that Canada Id is 1 and United States Id is 2

		var element = $(txtElement);
		var prop = '__advice' + txtElement.camelize();
		element[prop] = true;
		if (value == 1)
		{
			if (element.hasClassName('validate-zip-code'))
			{
				element.removeClassName('validate-zip-code');
				if ($('advice-validate-zip-code-' + txtElement))
				{
					$('advice-validate-zip-code-' + txtElement).hide();
					element.removeClassName('validation-failed');
				}
			}
			element.addClassName('validate-postal-code');
			ToggleValidation(element, txtElement, 'validate-postal-code');
		}
		else if (value == 2)
		{
			if (element.hasClassName('validate-postal-code'))
			{
				element.removeClassName('validate-postal-code');
				if ($('advice-validate-postal-code-' + txtElement))
				{
					$('advice-validate-postal-code-' + txtElement).hide();
					element.removeClassName('validation-failed');
				}
			}
			element.addClassName('validate-zip-code');
			ToggleValidation(element, txtElement, 'validate-zip-code');
		}
		else
		{
			if (element.hasClassName('validate-zip-code'))
			{
				element.removeClassName('validate-zip-code');
				if ($('advice-validate-zip-code-' + txtElement))
				{
					$('advice-validate-zip-code-' + txtElement).hide();
					element.removeClassName('validation-failed');
				}
			}

			if (element.hasClassName('validate-postal-code'))
			{
				element.removeClassName('validate-postal-code');
				if ($('advice-validate-postal-code-' + txtElement))
				{
					$('advice-validate-postal-code-' + txtElement).hide();
					element.removeClassName('validation-failed');
				}
			}
		}
	}
	
    /** This function limits the number of characters that can be typed into a textfield: 
    Used for multi line textboxes */
    function limitText(limitField, limitNum)
    {
        var returnValue; 
        if(limitField.value.length >= limitNum)
        {
            limitField.value = limitField.value.substr(0, limitNum)
	        returnValue=false; 
        }
        else
        { 
	        returnValue=true;
        } 
        return returnValue;
    } 
  
    function IncrementMembershipHitDetail(id, url)
    {
        var myAjax = new Ajax.Request(url,
            {
                method: "post", parameters : "id=" + id
            });
        return false;
    }

    function IncrementMembershipHitURL(id, url)
    {
        var myAjax = new Ajax.Request(url,
            {
                method: "post", parameters : "id=" + id
            });
        return false;
    }

    function IncrementMembershipHitEmail(id, url)
    {
        var myAjax = new Ajax.Request(url,
            {
                method: "post", parameters : "id=" + id
            });
        return false;
    }

  
  function PrintThisPage(content) 
  { 
   var sOption="toolbar=yes,location=no,directories=yes,menubar=yes,"; 
       sOption+="scrollbars=yes,width=750,height=600,left=100,top=25"; 

   var sWinHTML = $(content).innerHTML; 
   
   var winprint=window.open("","",sOption); 
       winprint.document.open(); 
       winprint.document.write('<html><LINK href=/content/css/layout.css rel=Stylesheet><body>'); 
       winprint.document.write(sWinHTML);          
       winprint.document.write('</body></html>'); 
       winprint.document.close(); 
       winprint.focus(); 
       winprint.print();
   }  
   
    function openContentWindow(content)
    {
		var contentWin = new Window({maximizable: false, resizable: false, hideEffect:Element.hide, showEffect:Element.show, minWidth: 10, destroyOnClose: true}); 
		contentWin.setContent(content, true, true);
		contentWin.show(); 
		// Set up a windows observer, check ou debug window to get messages myObserver = { onDestroy: function(eventName, win) { if (win == contentWin) { $('container').appendChild($('test_content')); contentWin = null; Windows.removeObserver(this); } debug(eventName + " on " + win.getId()) } } Windows.addObserver(myObserver);
    }

    function openWindow(portletId,url, name,mwidth,mheight)
    {
        var html = "";
        var dateParam = new Date().getMilliseconds();
        new Ajax.Request(url, {
              method: 'get',
              parameters:'_='+dateParam,
              onSuccess: function(transport) {
                html = transport.responseText;
                if(win==null)
                {
                    win = new Window('myWindow', {className:'alphacube', title: name, minimizable:true, maximizable:true, closable:true,onShow:update_layer_size});
                    win.toFront();
                }
                win.setHTMLContent(html);
	            win.width = mwidth;
	            win.height = mheight;
	            win.showCenter(true, 100, 200);
              }
            });
        
    }


    function openNewWindow(portletId, url, name, mwidth, mheight, min, max, close)
    {
        var newWin = null;
        var html = "";
        new Ajax.Request(url, {
              method: 'get',
              onSuccess: function(transport) {
                html = transport.responseText;
                if(newWin==null)
                {
                    newWin = new Window('myWindow', {className:'alphacube', title: name, minimizable:min, maximizable:max, closable:close});
                    newWin.setDestroyOnClose();
                    newWin.toFront();
	                //WindowCloseKey.init();
                }
                var content = '<div id=windowContent>'+html+'</div>';
                    
	            newWin.setHTMLContent(content);
	            newWin.width = mwidth;
	            newWin.height = mheight;
	            newWin.showCenter(true, 100, 200);
	            
              }
            });
    }

    function update_layer_size()
    { 
        
        setTimeout(function() { 
          var win = Windows.getFocusedWindow(); 
          win.updateHeight(); 
          win.setSize(win.getSize().width+2,win.getSize().height+2); 
         }, 100); 
    }
    
    function submitForm(vform){
        $(vform).submit();
    }
    
    function eventComponentSelection(target)
    {
        var myArr = ['regs.Attendees_0_ParallelItems_0_ComponentId','regs.Attendees_0_ParallelItems_1_ComponentId','regs.Attendees_0_ParallelItems_2_ComponentId']; 
        $A(myArr).each(
        function(item){
            if(item != target){
                $F('item').checked=false;
             }
          });
    }
    
    function confirmWindow(text)
    {
        Dialog.confirm(text, {width:200, okLabel: "Ok", buttonClass: "myButtonClass", id: "myDialogId", cancel:function(win) {return false}, ok:function(win) {return true;} });
    }

    function openSmallInfoDialog(text)
    {
        Dialog.info(text, {width:250, height:10, showProgress: true});
    }
    
    function openInfoDialog(text) 
    { 
        Dialog.info(text, {width:250, height:50, showProgress: true});
    }
    
    function openModalInfoDialog(text, modal) 
    { 
        Dialog.info(text, {width:250, height:50, showProgress: true, modal: modal});
    }
    
    function openModalInfoDialog(text, modal) 
    { 
        Dialog.info(text, {width:250, height:50, showProgress: true, modal: modal});
    }

    function closeInfoDialog(){
        Dialog.closeInfo();
    }

    function selectCities(id,text,value,selectid)
    {
        new Ajax.Request('/address/GetCities.aspx', {method:'post', parameters:'provinceId=' + id +'&text='+text+'&value='+value+'&modelName='+selectid, evalScripts: true});
    }

    function selectProvincesByCountry(countryId, modulePrefix, placeHolder)
    {
        var url = 'GetProvincesByCountry.aspx';
        var myAjax = new Ajax.Request(url,
            {
                method: "post", parameters : "modulePrefix=" + modulePrefix + "&countryId=" + countryId,
                onSuccess: function transResult (response)
                    {
                        document.getElementById('province' + placeHolder).innerHTML=response.responseText;
                    },
                onFailure: function transResult (response)
                    {
                        alert('Failure ' + response.responseText);
                    }
            });
        return false;
    }

    function selectEventsByEventGroup(eventGroupId, modulePrefix, placeHolder, firstOption)
    {
        var url = 'GetEventsByEventGroup.aspx';
        var myAjax = new Ajax.Request(url,
            {
                method: "post", parameters : "modulePrefix=" + modulePrefix + "&eventGroupId=" + eventGroupId + "&firstOption=" + firstOption,
                onSuccess: function transResult (response)
                    {
                        document.getElementById(placeHolder).innerHTML=response.responseText;
                    },
                onFailure: function transResult (response)
                    {
                        alert('Failure ' + response.responseText);
                    }
            });
        return false;
    }
    
    //Calendar scetup
    
    // This function gets called when the end-user clicks on some date.
    function selected(cal, date) {
      cal.sel.value = date; // just update the date in the input field.
      if (cal.dateClicked)
        // if we add this call we close the calendar on single-click.
        // just to exemplify both cases, we are using this only for the 1st
        // and the 3rd field, while 2nd and 4th will still require double-click.
        cal.callCloseHandler();
    }
    ////////////////////////////////////////////////////////////////////////
    // And this gets called when the end-user clicks on the _selected_ date,
    // or clicks on the "Close" button.  It just hides the calendar without
    // destroying it.
    function closeHandler(cal) {
      cal.hide();                        // hide the calendar
      _dynarch_popupCalendar = null;
    }

    // This function shows the calendar under the element having the given id.
    // It takes care of catching "mousedown" signals on document and hiding the
    // calendar if the click was outside.
    function showCalendar(id, format, showsTime, showsOtherMonths) {
      //var el = document.getElementById(id);
      var el = $(id);
      if (_dynarch_popupCalendar != null) {
        // we already have some calendar created
        _dynarch_popupCalendar.hide();                 // so we hide it first.
      } else {
        // first-time call, create the calendar.
        var cal = new Calendar(1, null, selected, closeHandler);
        // uncomment the following line to hide the week numbers
        // cal.weekNumbers = false;
        if (typeof showsTime == "string") {
          cal.showsTime = true;
          cal.time24 = (showsTime == "24");
        }
        if (showsOtherMonths) {
          cal.showsOtherMonths = true;
        }
        _dynarch_popupCalendar = cal;                  // remember it in the global var
        cal.setRange(1900, 2070);        // min/max year allowed.
        cal.create();
      }
      _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
      _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
      _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

      // the reference element that we pass to showAtElement is the button that
      // triggers the calendar.  In this example we align the calendar bottom-right
      // to the button.
      _dynarch_popupCalendar.showAtElement(el, "Br");        // show the calendar

      return false;
    }
    
    
    function checkPhoneFormat(ddlist) 
    {
	    if (ddlist.value > 0 && multiCountryIds != null)
	    {   
            var countryIds = multiCountryIds.split(';');
	        var useMulti = countryIds.indexOf(ddlist.value) >= 0;

	        var phoneContainer = $(ddlist).readAttribute('parentContainer');
            var phoneElements = null;
            if (phoneContainer != null) 
                phoneElements = $(phoneContainer).select('.phoneComponent');
            else
                phoneElements = $$('.phoneComponent');
            
            phoneElements.each(function(element) {
                var phone_id = element.readAttribute('phoneId');
                element.select('#multi_' + phone_id).each(function(elm) {
                    var madeChange = false;
                    if (!elm.visible() && useMulti) {
                        elm.show();
                        madeChange = true;
                    } else if (elm.visible() && !useMulti) {
                        elm.hide();
                        madeChange = true;
                    }
                    
                    if (madeChange) {
                        elm.select('input').each(function (elm2) {
                            elm2.value = '';
                        });                    
                    }
                });
                
                element.select('.validate-phone').each(function(elm) {
                    if (elm.visible() && useMulti) {
                        elm.hide();
                        elm.value = '';
                    }  else if (!elm.visible() && !useMulti) {
                        elm.show();
                        elm.value = '';
                    }
                });                
            });
          }
    }
    
    
    function selectProvinces(countryid,modulePrefix) {
    var url = 'GetProvinces.aspx';
    var myAjax = new Ajax.Request
      (
        url,
        {
          method: "post",
          parameters : "modulePrefix="+modulePrefix+"&countryId="+countryid,            
          onSuccess: function transResult (response) {

            document.getElementById('provincePlaceHolder').innerHTML=response.responseText;

          },
          onFailure: function transResult (response) {
            alert ('Failure'+response.responseText);
          }
        }
      );
      return false;
    }

    function selectCities(provinceid,modulePrefix) {
    var url = 'GetCities.aspx';
    var myAjax = new Ajax.Request
      (
        url,
        {
          method: "post",
          parameters : "modulePrefix="+modulePrefix+"&provinceId="+provinceid,            
          onSuccess: function transResult (response) {

            document.getElementById('cityPlaceHolder').innerHTML=response.responseText;

          },
          onFailure: function transResult (response) {
            alert ('Failure'+response.responseText);
          }
        }
      );
      return false;
    }

    function selectProvinces(countryId, modulePrefix, placeHolder) {
    var url = 'GetProvinces.aspx';
    var myAjax = new Ajax.Request
        (
            url, {
                method: "post",
                parameters : "modulePrefix=" + modulePrefix + "&countryId=" + countryId + "&placeHolder=" + placeHolder,            
                onSuccess: function transResult (response) {
                    document.getElementById('province' + placeHolder).innerHTML=response.responseText;
                },
                onFailure: function transResult (response) {
                    alert ('Failure'+response.responseText);
                }
            }
        );
        return false;
    }

    function selectCities(provinceId, modulePrefix, placeHolder) {
    var url = 'GetCities.aspx';
    var myAjax = new Ajax.Request
        (
            url, {
                method: "post",
                parameters : "modulePrefix=" + modulePrefix + "&provinceId=" + provinceId,            
                onSuccess: function transResult (response) {
                    document.getElementById('city' + placeHolder).innerHTML=response.responseText;
                },
                onFailure: function transResult (response) {
                    alert ('Failure'+response.responseText);
                }
            }
        );
        return false;
    }
    
    function selectContacts(membershipId, modulePrefix) {
    var url = 'GetContacts.aspx';
    var myAjax = new Ajax.Request
      (
        url,
        {
          method: "post",
          parameters : "modulePrefix=" + modulePrefix + "&membershipId=" + membershipId,            
          onSuccess: function transResult (response) {

            document.getElementById('contactPlaceHolder').innerHTML=response.responseText;

          },
          onFailure: function transResult (response) {
            alert ('Failure'+response.responseText);
          }
        }
      );
      return false;
    }

    function selectContactsWithFirstOption(membershipId, modulePrefix, firstOption) {
    var url = 'GetContacts.aspx';
    var myAjax = new Ajax.Request
      (
        url,
        {
          method: "post",
          parameters : "modulePrefix=" + modulePrefix + "&membershipId=" + membershipId + "&firstOption=" + firstOption,
          onSuccess: function transResult (response) {

            document.getElementById('contactPlaceHolder').innerHTML=response.responseText;

          },
          onFailure: function transResult (response) {
            alert ('Failure'+response.responseText);
          }
        }
      );
      return false;
    }
    
    function selectContactsWithPlaceholder(membershipId, modulePrefix, placeholder) {
    var url = 'GetContacts.aspx';
    var myAjax = new Ajax.Request
      (
        url,
        {
          method: "post",
          parameters : "modulePrefix=" + modulePrefix + "&membershipId=" + membershipId,            
          onSuccess: function transResult (response) {

            document.getElementById(placeholder).innerHTML=response.responseText;

          },
          onFailure: function transResult (response) {
            alert ('Failure'+response.responseText);
          }
        }
      );
      return false;
    }

    function ResetRadioButtonByName(radElementsName)
    {
	    var items = document.getElementsByName(radElementsName);
	    for (var i=0; i<items.length; i++)
	    {
	        items[i].checked = false;
	    }
    }

    /**
    * This public function performs the auto jump between fields.
    */
    function autoTab(fromField, toFieldId)
    {
        var toField = $(toFieldId);
        if (fromField.value.length == fromField.getAttribute("maxlength"))
            toField.focus();
    }

    /**
    * This public function performs the auto jump between fields and adds the number to a placeholder field
    */
    //function autoTab(index,fromField, toFieldId,appendId)
    function autoTab(id,fieldOne,fieldTwo, fieldTree,appendId)
    {
        var phoneArray = [$(fieldOne),$(fieldTwo),$(fieldTree)];
        if(id == 0 && $(fieldOne).value.length == $(fieldOne).getAttribute("maxlength"))
        {
            $(fieldTwo).focus();
        }
        
        if(id == 1 && $(fieldTwo).value.length == $(fieldTwo).getAttribute("maxlength"))
        {
            $(fieldTree).focus();
        }
        $(appendId).value = phoneArray[0].value + phoneArray[1].value + phoneArray[2].value;
    }
    
    
    function AjaxCallBack(url,params, callBack){
        new Ajax.Request(url, {
              method: 'get',
              parameters:params,
              onSuccess: this.callBack(callBack)
              
            });
    }
    
                        
	var globalHandlers = 
	{
		onCreate: function()
		{
			$('modifiedMessage').style.display="block";
		},

		onComplete: function(request) 
		{
			if (Ajax.activeRequestCount == 0)
			{
				$('modifiedMessage').style.display="none";
			}
		},
		onException: function(request, exception) {
    	if (request.transport)
    		request.transport.abort();

        // fixed. can throw multi-errors.		
        if (request.__start) {
	        Ajax.activeRequestCount_fixed--;
    		request.__start = false;
    	
	        if (Ajax.activeRequestCount_fixed == 0) {
	            Element.hide(element);
	        }

    		alert("Js Exception: " + exception);
    	}
    }
	};



	Ajax.Responders.register(globalHandlers);
