YUI().use('node', 'event-delegate', 'json-parse', 'io-base', function(Y) {

    if (Y.one('#events-ticket-quantity'))
    {
        Y.one('#events-ticket-quantity').on('click', function(e)
        {
            alert("These tickets can only be added to your basket one at a time as we need to verify the details of each ticket holder. \n\nTo add multiple tickets, first add one, then you will be invited to add more.");
        });


    }

    var popup = function(el) {

        var defaults = {
            w: 400,
            h: 400,
            msgFormat: '%remaining% characters remaining'
        }

        var popupConfig = {
            'popup-spread-the-word': {
                w: 460,
                h: 500
            },
            'popup-report-concern': {
                w: 460,
                h: 600
            },
            'popup-spread-the-word-ft': {
                w: 460,
                h: 500
            }
        }

        var elCfg = popupConfig[el.get('id')];
        elCfg = Y.merge(defaults, elCfg);
        
        return window.open(el.getAttribute('href'),
        "mmPop",
        "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes,width=" + elCfg.w + ",height=" + elCfg.h);
    }

    //popup links in new window
	Y.delegate("click", function(e) {
		e.halt();        
        popup(this);

	}, "#custom-doc", "a.popup");

    //advanced search sections
	Y.delegate("click", function(e) {
        if (this.hasClass('toggle-collapsed')){
            this.replaceClass('toggle-collapsed', 'toggle-expanded');
            this.next().removeClass('hidden');
        }else{
            this.replaceClass('toggle-expanded', 'toggle-collapsed');
            this.next().addClass('hidden');
        }

	}, ".advanced-search-left", "h2");
     var  currentPhoto = 0;
    //profile photo toggles
    Y.delegate("click", function(e) {
        e.halt();

        var i = this.getAttribute('id').substr(5);
        Y.all('.profile-thumbnails .profile-thumb').removeClass('selected');
        this.addClass('selected');
        Y.all('.profile-photo-show .profile-photo').addClass('hidden');        
        Y.one('#photo'+i).removeClass('hidden');
        currentPhoto = i;

	}, ".profile-thumbnails", "img");


      var profileThumbnails = Y.all(".profile-thumb");


    //popup links in new window
	Y.on("click", function(e) {
            e.halt();

            Y.all('.profile-thumbnails .profile-thumb').removeClass('selected');
            Y.all('.profile-photo-show .profile-photo').addClass('hidden');

            if(this.get('id') == 'next-button') {

                // current photo class is last
                if( (profileThumbnails.size()  - 1) == currentPhoto) {
                    Y.one('#photo0').removeClass('hidden');
                    currentPhoto = '0';

                }else {
                    currentPhoto  = ++currentPhoto ;
                    Y.one('#photo'+ currentPhoto).removeClass('hidden');

                }

            }else {

               currentPhoto =   (currentPhoto == 0 ? (profileThumbnails.size() ) -1 : -- currentPhoto) ;
               Y.one('#photo'+ currentPhoto ).removeClass('hidden');
            }

	}, ".photo-button");

        Y.all('.large-image img').on('load', function(e)
        {
            var photo_dimensions = new Array();

            Y.all ('.large-image img').each(function(node){
                  photo_dimensions.push(this.getStyle('height'));

             });


//            if(photo_dimensions){
//                photo_dimensions.sort();
//                photo_dimensions.reverse();
//                if(Y.one('.profile-photos')){
//                     Y.one('.profile-photos').setStyle('height',  photo_dimensions[0]);
//                }
//           }
        });

    
        

    function templateCharacterHint(elCfg, el)
    {
        var remaining = elCfg.max - (el.value.length);
        var txt = elCfg.msgFormat.replace('%remaining%', remaining, 'gi');
        txt = txt.replace('%min%', elCfg.min, 'gi');
        return txt;
    }

    //character counts for textareas
    Y.all('form .charcount').each(function(node){

        var defaults = {
            min: 0,
            max: 400,
            msgFormat: '<strong>%remaining%</strong> characters remaining'
        }

        var inputConfig = {
            introduction_text: {
                min: 200,
                max: 4000,
                msgFormat: '<strong>%remaining%</strong> characters remaining (%min% characters minimum)'
            },
            dislikes_text: {
                max: 150
            }
        };

        var elCfg = inputConfig[node.get('id')];
        elCfg = Y.merge(defaults, elCfg);

        var el = Y.Node.getDOMNode(node);
        var c = document.createElement('span');
        c.className = 'charcount-remaining';
        
        el.parentNode.insertBefore(c, el);
        
        updateCount = function(){
            var remaining = elCfg.max - (el.value.length);
            if (remaining < 0) {
                c.className = 'charcount-error';
            } else {
                c.className = 'charcount-remaining';
            }
            c.innerHTML = templateCharacterHint(elCfg, el);
        }
        updateCount();
        node.on('keyup', updateCount);
    });

    Y.on('submit', function(e){
        if (!document.getElementById('visibility_status-hidden').checked){
            return;
        }
        e.halt();

        var msg = "Hiding your profile from the public means you will not appear in searches and no new people will be able to conatct you.\n\n"
      + "Are you sure you want to hide your profile?";

        msg = Y.one('#vis-message .content').get('text');
        if (confirm(msg)){
            this.submit();
        }

    }, '#visibility-form');
    
    /** When send-to-friend button is clicked show the form*/
    if (Y.one('#send-to-friend'))
    {
    Y.one('#send-to-friend').on("click", function(e) {
         e.halt();
         Y.one('#quiz-content-pad-sides').setStyle('display', 'block');
         Y.one('#quiz-content-pad-sides').setStyle('visibility', 'visible');

    });}

    /** When relationship is selected in basic search form disable dating option*/

       Y.on('change', function(e)
       {

           if (document.getElementById('seeking_status').value=="both" || document.getElementById('seeking_status').value=="relationship" )
           {
               Y.one('#looking_for-dating').set('disabled', true);
               Y.one('#looking_for-fsi').set('checked', true);
           }
           else
           {
               Y.one('#looking_for-dating').set('disabled', false);
           }

       }, '#seeking_status');

       if(document.getElementById('seeking_status'))
       {

           if (document.getElementById('seeking_status').value=="both" || document.getElementById('seeking_status').value=="relationship" )
           {
               Y.one('#looking_for-dating').set('disabled', true);
               Y.one('#looking_for-fsi').set('checked', true);
           }
           else
           {
               Y.one('#looking_for-dating').set('disabled', false);
           }
       }

 
       
/** set town to choose and enable town when county is changed in general profile page*/

        var townReload = {

           fetchTowns : function (countyId)
           {
		var handleSuccess = function(ioId, o)
                {
			if(o.responseText !== undefined)
                        {
				var html = Y.JSON.parse(o.responseText);

                                //Y.log(html);

                                var nodes = Y.all('#town_id option');
                                nodes.remove();

                                var townId = document.profileBuilderForm.town_id;

                                for (var i = 0; i < html.length; i++)
                                {
                                    townId.options[i] = new Option(html[i].town, html[i].id);
                                }


                                

                                /*

                                

                                Y.one('#town_id').prepend('<option selected="selected" label="choose" value="">choose</option>');
                                Y.one('#town_id').append(html);
                                
                                //Y.log();
                                //Y.one('#town_id').set('innerHTML', html);
                                //alert(html); */
			}
		};

                //Y.on('io:complete', handleSuccess);

		/* Configuration object for POST transaction */
		var cfg = {
			method: "POST",
			data: "countyId=" + countyId,
                        on: {
                            success: handleSuccess
                        }
		};
 
		//The URL of the resource to which we're POSTing data:
		var sUrl = "/users/profile/fetch-towns";
		request = Y.io(sUrl, cfg);
           },

           fetchCounties : function (countryId)
           {
               var handleSuccess = function(ioId, o)
                {
			if(o.responseText !== undefined)
                        {
				var html = Y.JSON.parse(o.responseText);

                                var nodes = Y.all('#county_id option');
                                nodes.remove();

                                nodes = Y.all('#town_id option');
                                nodes.remove();

                                var countyId = document.profileBuilderForm.county_id;
                                var townId = document.profileBuilderForm.town_id;

                                townId.options[0] = new Option('choose', '');

                                for (var i = 0; i < html.length; i++)
                                {
                                    countyId.options[i] = new Option(html[i].county, html[i].id);
                                }

			}
		};

		/* Configuration object for POST transaction */
		var cfg = {
			method: "POST",
			data: "countryId=" + countryId,
                        on: {
                            success: handleSuccess
                        }
		};

		//The URL of the resource to which we're POSTing data:
		var sUrl = "/users/profile/fetch-counties";
		request = Y.io(sUrl, cfg);
           }

       };

        /** set county to choose and disable town when country is changed in general profile page*/
       Y.on('change', function(e)
       {
           if (Y.one('#country_id') && Y.one('#county_id'))
             {
                townReload.fetchCounties(Y.one('#country_id').get('value'));
             }


         if ('5' == Y.one('#country_id').get('value'))
         {
             Y.one('#postcode').setStyle('display', 'none');
             Y.one('#postcode-not-required').setStyle('display', 'block');
         }
         else
         {
             Y.one('#postcode').setStyle('display', 'block');
             Y.one('#postcode-not-required').setStyle('display', 'none');
         }

         document.getElementById('county_id').value="" ;
         Y.one('#town_id').set('disabled', true);

       }, '.profile_builder_form #country_id');

       if (Y.one('#country_id') && Y.one('#postcode'))
       {
        if ('5' == Y.one('#country_id').get('value'))
         {
             Y.one('#postcode').setStyle('display', 'none');
             Y.one('#postcode-not-required').setStyle('display', 'block');
         }
         else
         {
             Y.one('#postcode').setStyle('display', 'block');
             Y.one('#postcode-not-required').setStyle('display', 'none');
         }
       }

       Y.on('change', function(e)
       {
         if (Y.one('#town_id') && Y.one('#county_id'))
         {
            townReload.fetchTowns(Y.one('#county_id').get('value'));
         }

         Y.one('#town_id').set('disabled', false);
         document.getElementById('town_id').value="" ;

       }, '.profile_builder_form #county_id');

       function checkMaritalStatus(value)
       {
           if ('5' == value || '6' == value)
           {
               Y.one('#dating').set('disabled', true);
               Y.one('#dating_looking_for').set('disabled', true);
           }
           else
           {
               Y.one('#dating').set('disabled', false);
               Y.one('#dating_looking_for').set('disabled', false);
           }
       }

       /** My profile general info page when relationship is selected in marital status disable dating option*/
       if (Y.one('#marital_status_id'))
       {
           checkMaritalStatus(Y.one('#marital_status_id').get('value'));

           Y.one('#marital_status_id').on('change', function(e)
           {
               checkMaritalStatus(Y.one('#marital_status_id').get('value'));
           });
       }

    /**
     * When country option chosen, set county options
     */
    function handleRegistrationCountryChange(e) {
        var countryId = this.get('value');

        var county = Y.one('#form-users-register #county_id');
        
        if ('' == countryId){
            county.set('disabled', true);
            return;
        }

        var uri = "/users/auth/get-county-options/id/" + countryId;

        // Update element with response (select)
        function complete(id, o, args) {
            var data = o.responseText;
            Y.one('#county_id').get('parentNode').set('innerHTML', data);
        };

        Y.on('io:complete', complete, Y);

        var request = Y.io(uri);
    }
    Y.on('change', handleRegistrationCountryChange, '#form-users-register #country_id');

    Y.on('click', function(e){
        if (!confirm('Really delete this item from your basket?')){
            e.halt();
        }
    }, '.basket-container .basket-remove-item');

    Y.on('click', function(e){
        if (!confirm('Really empty your basket?')){
            e.halt();
        }
    }, '.basket-empty-all');

    var region = Y.one('#advanced-search-form #region');

    if (region)
    {
        region.on('change', function(e) {

            var postcodePre = Y.one('#muddy-region label');
            var postcodeEl = Y.one('#advanced-search-form #distance');
            var postcodePost = Y.one('#advanced-search-form #postcode_prefix');

            if (postcodeEl)
            {

            
                if (0 != region.get('value'))
                {
                    postcodeEl.set('disabled', true);
                    postcodePost.setStyle('color', '#999999');
                    postcodePre.setStyle('color', '#999999');
                }
                else
                {
                    postcodeEl.set('disabled', false);
                    postcodePost.setStyle('color', '#214D6A');
                    postcodePre.setStyle('color', '#214D6A');
                }
            }


        });
    }

    if (Y.one('#confirmBlock'))
    {
        Y.one('#confirmBlock').on('click', function(e){
            e.halt();

            var answer = confirm("Are you sure you want to block this person? If you block them they will no longer appear in your searches, and you will not be able to correspond with messages. If this person is in your favourites or profile views lists they will be removed.")
            if (answer){
                    window.location = Y.one('#confirmBlock').get('href');
            }
            else
            {
                e.preventDefault();
            }
        });
    }

    if (Y.one('.payment #country'))
    {
        var val = Y.one('.payment #country').get('value');

        if (val != 'GB')
        {
            Y.one('#postcode-label label').removeClass('required');
            Y.one('#county-label label').removeClass('required');
        }
        else
        {
            Y.one('#postcode-label label').addClass('required');
            Y.one('#county-label label').addClass('required');
        }

        Y.one('.payment #country').on('change', function(e)
        {
            val = Y.one('.payment #country').get('value');

            if (val != 'GB')
            {
                Y.one('#postcode-label label').removeClass('required');
                Y.one('#county-label label').removeClass('required');
            }
            else
            {
                Y.one('#postcode-label label').addClass('required');
                Y.one('#county-label label').addClass('required');
            }

        });
    }

});

// This function is used on the FAQ page to show and hide different answers.
// Brought in from old website, unmodified. Could be improved.

function show_answer(id){
  var tags = document.getElementsByTagName('div');
  for (var count = 0; count < tags.length; count++) {
    if (tags[count].id.substring(2, 0) == 'q-') {
      tags[count].style.display = 'none';
    }
  }
  document.getElementById(id).style.display = '';
}

YUI().use('node', 'io-base', 'cookie', function(Y) {

  var locked = false;
  var currentDomain = "." + document.domain;
  var gogo = false;

  if (Y.one('#keep_alive')) {

    window.setInterval(function() {

      if (!locked) {
        var body = Y.one('#body');
        var subject = Y.one('#subject');
        
        bodyText = body.get('value');
        subjectInput = subject.get('value');

        Y.Cookie.set("message_text", bodyText, { path: '/', domain: currentDomain, expires: new Date("January 12, 2025") });

        Y.Cookie.set("message_subject", subjectInput, { path: '/', domain: currentDomain, expires: new Date("January 12, 2025") });

        Y.io("/default/index/ping");
      }
      
    }, 5000);

    Y.one('#submit').on('click', function(e) {
      
      if (!gogo) {
        e.preventDefault();
        var lol = {
                method: "GET",
                data: "",
                on: {
                    success: function (oId, res) {
                      var text = res.responseText;

                      //if ('true' == text) {
                        locked = true;
                        Y.Cookie.remove("message_text", { path: '/', domain: currentDomain });

                        Y.Cookie.remove("message_subject", { path: '/', domain: currentDomain });
                        gogo = true;
                        document.getElementById('submit').click();
                      //} else {
                      //  gogo = true;
                      //  document.getElementById('submit').click();
                      //}
                    }
                }
        };

        Y.io("/session_check.php", lol);
      }
    });

    Y.one('#cancel').on('click', function(e) {
      locked = true;
      Y.Cookie.remove("message_text", { path: '/', domain: currentDomain });

      Y.Cookie.remove("message_subject", { path: '/', domain: currentDomain });
    });

    if (Y.one('#recover-message-panel')) {
      Y.one('#recover-message').on('click', function(e) {
        e.preventDefault();

        Y.one('#recover-message-panel').setStyle('display', 'none');
        var recoveryText = Y.one('#draft-text').get('value');
        var recoverySubject = Y.one('#draft-subject').get('value');

        var body = Y.one('#body');
        var subject = Y.one('#subject');

        body.set('value', recoveryText);
        subject.set('value', recoverySubject);
      });
    }
    
  }
  
  // page click tracking
  var trackers = Y.all('a.track_click');
  trackers.each(function(node) {
	  node.on('click', function(e){
		  e.preventDefault();
	      var track = {
              method: "GET",
              data: "referrer=" + location.href + "&target_section=" + node.getAttribute("data-target") + "&target=" + node.getAttribute("href") + "&link_location=" + node.getAttribute("data-link_location"),
			  on: {
			  	success: function() {
					location.href = node.getAttribute("href");
				}
			  }
	      };
		  Y.io("/default/index/track", track);
		  
	 });
  });
  
  var login_field = Y.one("#login-main input#login_user_id");
  if (login_field) {
  	login_field.focus();
  }
  
});
