// Determine whether or not JQuery is loaded
try {
  var junk=jQuery;
  jQueryIsLoaded=true;
} catch(err) {
  var jQueryIsLoaded=false;
}

// --------------------------------------------------------------------
/**
 * ?
 */
function windowme(url, name, params) {
  var mywindow=window.open (url, name, params);
  mywindow.moveTo('300', '200');
  return false;
}

// --------------------------------------------------------------------
/**
 * Subscribe an email address entered in the header form on every page,
 * via various referral popups, or competition page.
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id the CSS ID of the calling form, from which the IDs of
 * submit button, progress bar and note fields can be deduced
 * @return
 */
function subscribe(city, lang, form_id) {

  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');
  $("#" + form_id + "-note").html('');

  var str = $("#" + form_id).serialize();
  $.ajax({
    type: "POST",
    url: '/' + city + '/' + lang + '/ajax/subscribe.php',
    data: str,
    success: function(msg) {

      $("#" + form_id + "-note").ajaxComplete(function(event, request, settings){
        if (msg != 'OK') {
          $("#" + form_id + "-progressbar").html('');
          $("#" + form_id + "-button").css('display', 'block');
          $(this).html(msg);

        } else {
          // All OK.  Prevent any previous error msg flashing up during redirect
          $("#" + form_id + "-note").html('');

          // Find the calling page
          var p=location.pathname.split('/');
          var dir=p[p.length-2];

          if (dir=='competition') {
            // The competition page should just reload
            window.location.reload();

          } else if (dir=='popups') {
            // If the subscribe box was used in a popup the popup should be closed and the redirect applied to the parent window
            // parent.location = '/' + city + '/' + lang + '/register.php?n';
            parent.window.location.href = parent.window.location.href;
            parent.$.colorbox.close();

          } else {
            //location = '/' + city + '/' + lang + '/register.php?n';
            window.location.reload();
          }
        }
      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Process an invitation code entered on the front index.php page, and
 * bounce the user to the appropriate tour.  Note that invite_codes.php
 * returns a JSON response.
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id the CSS ID of the calling form, from which the IDs of
 * submit button, progress bar and note fields can be deduced
 */
function inviteCodeSubmit(city, lang, form_id) {

  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" height="10px" />');
  var str = $("#" + form_id).serialize();

  $.ajax({
    type: "POST",
    url: '/' + city + '/' + lang + '/ajax/invite_codes.php',
    data: str,
    dataType: 'json',
    success: function(data){
      $("#" + form_id).ajaxComplete(function(event, request, settings) {
        // alert('status : ' + data.status + "\nmsg : " + data.msg);
        if (data.status=="OK") {
          // data.status is 'OK', data.msg is our destination code
          switch(data.msg) {
            case '1':
              location = 'tours/charity/index.php';
              break;
            case '2':
              location = 'tours/merchants/index.php';
              break;
            case '3':
              location = 'tours/operators/index.php';
              break;
            case '4':
              location = 'tours/general/index.php';
              break;
            // Access to the test deal for Rio. Using 7 rather than 5 as 5 and 6 were used in the PRG Live site.
            case '7':
              location = 'deal.php';
              break;
          }
        } else {
          // Some problem, data.msg is a localised msg from invite_codes.php
          $("#" + form_id + "-progressbar").html('');
          $("#" + form_id + "-button").css('display', 'inline');
          $("#" + form_id + "-note").attr("class", "errorMessage");
          $("#" + form_id + "-note").html("<br>" + data.msg); // <br> required for placement of txt
        }
      });
    }
  });
  return false;
}

// --------------------------------------------------------------------
/**
 * Full registration from either register.php or payment.php.  Expects a
 * JSON response.
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id The CSS ID of the form.  Note the ID of the submit button
 * should be the same, with "-button" appended, and the ID where the progressbar
 * is displayed should use be the same, with "-progressbar" appended.
 * @return
 */
function register(city, lang, form_id) {
    $("#" + form_id + "-button").css('display','none');
    $("#" + form_id + "-note").html('&nbsp;');
    $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');

    var str = $("#" + form_id).serialize();
    $.ajax({
        type: "POST",
        url:  '/' + city + '/' + lang + '/ajax/register.php',
        data: str,
        dataType: 'json',
        success: function(data) {
            $("#" + form_id + "-note").ajaxComplete(function(event, request, settings) {
                $("#" + form_id + "-progressbar").html('');

                if (data.status == 'OK') {
                    // Prevent any previous msg from flashing up before the bounce
                    $("#" + form_id + "-note").removeClass('errorMessage');
                    $("#" + form_id + "-note").html('');

                    // If coming from the new subscribe popup, close it and refresh the
                    // parent window.  ajax/register.php will have set a SESSION var which
                    // will then trigger 2nd popup.
                    if (form_id == 'register-popup') {
                        parent.window.location.reload(true);
                        parent.$.colorbox.close();
                    } else {
                        //DOS - New subscribe process - Redirect to the homepage and refresh
                        //location = "/" + city + "/" + lang + '/signup_friends.php?n';
                        location = "/" + city + "/" + lang + '/index.php';
                    }

                } else if (data.status == 'Failed') {
                    $("#" + form_id + "-button").css('display','block');
                    $("#" + form_id + "-note").attr("class", "errorMessage");
                    $("#" + form_id + "-note").html(data.msg);

                } else if (data.status == 'reload') {
                    // Prevent any previous msg from flashing up before the reload
                    $("#" + form_id + "-note").removeClass('errorMessage');
                    $("#" + form_id + "-note").html('');
                    location.reload();
                }
            });
        }
    });
}

// --------------------------------------------------------------------
/**
 * Submit a new hip tip.  Expects a JSON response from ajax/add_hip_tip.php.
 * Used for both holding and live sites.
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id the CSS ID of the calling form, from which the IDs of
 * submit button, progress bar and note fields can be deduced
 */
function hipTipSubmit(city, lang, form_id) {

  $("#" + form_id + "-note").html(''); // Zap any previous msg
  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');

  var str = $("#" + form_id).serialize();
  $.ajax({
    type: "POST",
    url: '/' + city + '/' + lang + '/ajax/add_hip_tip.php',
    data: str,
    dataType: 'json',
    success: function(data) {
      $('#' + form_id + "-note").ajaxComplete(function(event, request, settings) {
        if (data.status != 'OK') {
          $("#" + form_id + "-progressbar").html('');
          $("#" + form_id + "-button").css('display', 'block');
          $(this).attr("class", "errorMessage");
          $(this).html(data.msg);
        } else {
          // Prevent any old msg from flashing up during redirect
          $("#" + form_id + "-note").html('');
          location = 'hip_tips_done.php';
        }
      });
    }
  });
}

// --------------------------------------------------------------------
function setLength() {
  passwordField.addStyleClass("password-style");
}

// Makes the first letter of the data entered a capital letter. Used for Firstname, Surname etc.
// --------------------------------------------------------------------
function initialCap(field) {
  field.value = field.value.substr(0, 1).toUpperCase() + field.value.substr(1);
}

// --------------------------------------------------------------------
/**
 * Update personal profile info, called from profile pages
 *
 * @param city The city requested in the URL, eg prague
 * @param lang The lang requested in the URL, eg en
 * @param target The CSS ID of the div to display result or error in
 * @param msgSucc Message sent back on success
 */
function updatePersonalInfo(city, lang, target, msgSucc) {

    var pi_button=$("#pi-button");
    var pi_inprogress=$("#pi-inprogress");
    var old_phone_country_code=$("#old_phone_country_code");
    var phone_country_code=$("#phone_country_code");
    var old_mobile=$("#old_mobile");
    var mobile=$("#mobile");
    var sms_msg=$('#sms_msg');
    var show_verification=false;

    var str = $("#pi-form").serialize();

    pi_button.css('display', 'none');
    pi_inprogress.html('<img src="/images/loading.gif" />');

    $.ajax({
        type: "POST",
        url: "/" + city + "/" + lang + "/ajax/update-profile.php",
        data: str,
        dataType: 'json',
        success: function(response) {
            pi_inprogress.html('');
            pi_button.css('display', 'block');
            $("#" + target).ajaxComplete(function(event, request, settings) {
                $(this).removeClass();
                if (response.status == 'OK') {
                    result = msgSucc;
                    $(this).addClass('success');

                    // console.log('old : ' + old_phone_country_code.val() + ' ' + old_mobile.val());
                    // console.log('new : ' + phone_country_code.val() + ' ' + mobile.val());

                    // If the phone number details were just changed, display the verify link
                    if (old_phone_country_code.val()!=phone_country_code.val()) {
                        // console.log('pcc mismatch!');
                        show_verification=true;
                    }
                    if (old_mobile.val()!=mobile.val()) {
                        // console.log('m mismatch!');
                        show_verification=true;
                    }

                    if (show_verification==true) {
                        // Display the phone verification link
                        $('#phone_status').removeClass("hidden");
                        $('#send_sms').removeClass("hidden");
                        if (!sms_msg.hasClass('hidden')) {
                            sms_msg.addClass("hidden");
                        }
                        // And update the "old" fields with the new details so we can watch
                        // for future changes
                        old_phone_country_code.val(phone_country_code.val());
                        old_mobile.val(mobile.val());

                    } else {
//                        $('#phone_status').addClass("hidden");
//                        $('#send_sms').addClass("hidden");
//                        $('#sms_msg').addClass("hidden");
                    }

                } else {
                    result = response.msg;
                    $(this).addClass('error');
                }
                $(this).html(result);
            });
        }
    });
}

// --------------------------------------------------------------------
/**
 * Update password, called from profile pages
 *
 * @param city The city requested in the URL, eg prague
 * @param lang The lang requested in the URL, eg en
 * @param target The CSS ID of the div to display result or error in
 * @param msgSucc Message sent back on sucess
 */
function changePassword(city, lang, target, msgSucc) {
  $('#pp-button').css('display', 'none');
  $("#pp-inprogress").html('<img src="/images/loading.gif" />');
  var str = $("#pp-form").serialize();
  $.ajax({
    type: "POST",
    url: "/" + city + "/" + lang + "/ajax/update-profile.php",
    data: str,
    success: function(msg){
      $('#pp-inprogress').html('');
      $('#pp-button').css('display', 'block');
      $("#" + target).ajaxComplete(function(event, request, settings){
        $(this).removeClass();
        if(msg == 'OK')  {
          result = msgSucc;
          $(this).addClass('success');
        }else {
          result = msg;
          $(this).addClass('error');
        }
        $(this).html(result);
      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Update language preference, called from profile pages
 *
 * @param city The city requested in the URL, eg prague
 * @param lang The lang requested in the URL, eg en
 * @param target The CSS ID of the div to display result or error in
 * @param msgSucc Message sent back on sucess
 */
function changeLanguage(city, lang, target, msgSucc) {
  $('#pl-button').css('display', 'none');
  $("#pl-inprogress").html('<img src="/images/loading.gif" />');
  var str = $("#pl-form").serialize();
  $.ajax({
    type: "POST",
    url: "/" + city + "/" + lang + "/ajax/update-profile.php",
    data: str,
    success: function(msg){
      $('#pl-inprogress').html('');
      $('#pl-button').css('display', 'block');
      $("#" + target).ajaxComplete(function(event, request, settings){
        $(this).removeClass();
        if(msg == 'OK') {
          result = msgSucc;
          $(this).addClass('success');
        } else {
          result = msg;
          $(this).addClass('error');
        }
        $(this).html(result);
      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Update members email preferences, called from profile pages
 *
 * @param city The city requested in the URL, eg prague
 * @param lang The lang requested in the URL, eg en
 * @param target The CSS ID of the div to display result or error in
 * @param msgSucc Message sent back on sucess
 */
function changeEmailPrefs(city, lang, target, msgSucc) {
  $('#pe-button').css('display', 'none');
  $("#pe-inprogress").html('<img src="/images/loading.gif" />');
  var str = $("#pe-form").serialize();
  $.ajax({
    type: "POST",
    url: "/" + city + "/" + lang + "/ajax/update-profile.php",
    data: str,
    success: function(msg){
      $('#pe-inprogress').html('');
      $('#pe-button').css('display', 'block');
      $("#" + target).ajaxComplete(function(event, request, settings){
        $(this).removeClass();
        if(msg == 'OK') {
          result = msgSucc;
          $(this).addClass('success');
        } else {
          result = msg;
          $(this).addClass('error');
        }
        $(this).html(result);
      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Handle a login form submission
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id the CSS ID of the calling form, from which the IDs of
 * submit button, progress bar and note fields can be deduced
 */
function loginSubmit(city, lang, form_id) {
  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');
  $("#" + form_id + "-note").html('');
  var str = $("#" + form_id).serialize();

  $.ajax({
    type: "POST",
    url: '/' + city + '/' + lang + '/ajax/member_login.php',
    data: str,
    dataType: 'json',
    success: function(data) {
      $("#" + form_id + "-note").ajaxComplete(function(event, request, settings) {

        // In all cases remove progress bar and show submit button again
        $("#" + form_id + "-progressbar").html('');
        $("#" + form_id + "-button").css('display', 'block');

        // What happens after successful login ?
        if (data.status == 'OK') {

          // source field is available but not used atm
          // source=$("#" + form_id + " input[name=source]").val();

		  // Find the calling page - DOS - Used in login_popup.php
          var p=location.pathname.split('/');
          var dir=p[p.length-2];
		  var file=p[p.length-1];

		  if(file == 'login_popup.php'){
			// If the login form was used in a popup the popup should be closed and the redirect applied to the parent window
            parent.$.fn.colorbox.close();
			parent.location.reload();
		  } else {
			// Default action is to reload current page
			window.location.reload();
		  }
          
        } else if (data.status == "redirect") {
            // A redirect was requested
            // $(this).html('Redirecting ...');

			//Default action is to use the redirect passed in as a param
			location = data.msg;
		  
        } else {
          // An error, display it and bail
          $(this).html(data.msg);
        }
      });
    }
  });
}

// --------------------------------------------------------------------
/*
 * Reset a user's password, used on the password_reset.php page.  Expects a
 * JSON response from ajax/password_reset.php
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id the CSS ID of the calling form, from which the IDs of
 * submit button, progress bar and note fields can be deduced
 * @return
 */
function password_reset(city, lang, form_id) {
  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');
  $("#" + form_id + "-note").html('');
  var formdata = $("#" + form_id).serialize();
  $.ajax({
    type: "POST",
    url: "/" + city + "/" + lang + "/ajax/password_reset.php",
    data: formdata,
    dataType: 'json',
    success: function(data) {
      $("#" + form_id + "-note").ajaxComplete(function(event, request, settings) {
        $("#" + form_id + "-progressbar").html('');
        $(this).html(data.msg);
        if (data.status!="OK") {
          $("#" + form_id + "-button").css('display', 'block');
        }
      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Set a user's password; called from password_set.php.  Expects a JSON
 * response.
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id the CSS ID of the calling form, from which the IDs of
 * submit button, progress bar and note fields can be deduced
 */
function password_set(city, lang, form_id) {
  $("#" + form_id + "-note").html(''); // Zap any previous msg
  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');
  var str = $("#" + form_id).serialize();
  $.ajax({
    type: "POST",
    url: "/" + city + "/" + lang + "/ajax/password_set.php",
    data: str,
    dataType: 'json',
    success: function(data){
      $("#" + form_id + "-note").ajaxComplete(function(event, request, settings) {
        $("#" + form_id + "-progressbar").html('');

        if (data.status=="OK") {
          // Replace the whole form with the success msg
          $('div.blank-postcard').html(data.msg);
        } else {
          $(this).html(data.msg);
          $("#" + form_id + "-button").css('display', 'block');
        }
      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Called from payment page
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id the CSS ID of the calling form, from which the IDs of
 * submit button, progress bar and note fields can be deduced
 * @return
 */
function bankTransferSendSMS(city, lang, form_id) {
  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');
  $("#" + form_id + "-note").html('');
  var str = $("#" + form_id).serialize();
  $.ajax({
    type: "POST",
    url: "/" + city + "/" + lang + "/ajax/send_bank_transfer_sms.php",
    data: str,
    success: function(msg) {
      var retArr=msg.split('-'); // we pass the ${status}-${smscode} as ajax result
      $("#" + form_id + "-note").ajaxComplete(function(event, request, settings) {
        $("#" + form_id + "-progressbar").html('');
        if (retArr[0] != 'OK') {
          $("#" + form_id + "-button").css('display', 'block');
          $(this).html(msg);         
        } else {
          //$("#smsverificationbox_div").css('display', 'block');
          window.location='./thankyou.php?ref='+retArr[1];
        }
      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Called from payment page
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id the CSS ID of the calling form, from which the IDs of
 * submit button, progress bar and note fields can be deduced
 * @return
 */
function checkSMSVerificationCode(city, lang, form_id) {
  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');
  var str = $("#" + form_id).serialize();
  $.ajax({
    type: "POST",
    url: "/" + city + "/" + lang + "/ajax/check_bank_transfer_sms.php",
    data: str,
    success: function(msg) {
      $("#" + form_id + "-note").ajaxComplete(function(event, request, settings){
        if (msg != 'OK') {
          $("#" + form_id + "-progressbar").html('');
          $("#" + form_id + "-button").css('display', 'block');
          $(this).html(msg);
        } else if (msg == 'OK') {
          $("#smsverificationbox_div").css('display', 'none');
          $("#" + form_id + "-note").html('');
          //$("#note_success").css('display', 'block');
          window.location='./thankyou.php';
        }
      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Process a submission from the "contact us" form on the about us page,
 * and from the "suggest a freebie" form on the freebies page.
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id the CSS ID of the calling form, from which the IDs of
 * submit button, progress bar and note fields can be deduced
 * @return
 */
function commentSubmit(city, lang, form_id) {
  $("#" + form_id + "-note").html(''); // Zap any previous msg
  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');
  var str = $("#" + form_id).serialize();
  $.ajax({
    type: "POST",
    url: "/" + city + "/" + lang + "/ajax/contact.php",
    data: str,
    dataType: 'json',
    success: function(data) {
      $("#" + form_id + "-note").ajaxComplete(function(event, request, settings) {
        $("#" + form_id + "-progressbar").html('');
        $("#" + form_id + "-button").css('display', 'block');
        $(this).html(data.msg);
      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Process a comment submitted on the "Dicsuss the deal" page.
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id the CSS ID of the calling form, from which the IDs of
 * submit button, progress bar and note fields can be deduced
 * @return
 */
function dealCommentSubmit(city, lang, form_id) {

  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');
  var str = $("#" + form_id).serialize();

  $.ajax({
    type: "POST",
    url: "/" + city + "/" + lang + "/ajax/comment.php",
    data: str,
    success: function(msg) {
      $("#" + form_id + "-note").ajaxComplete(function(event, request, settings){
        $("#" + form_id + "-progressbar").html('');
        $("#" + form_id + "-button").css('display', 'block');
        $(this).html(msg);
      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Process a claim freebie request, called on freebies.php
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id the CSS ID of the calling form, from which the IDs of
 * submit button, progress bar and note fields can be deduced
 */
function getFreebie(city, lang, form_id) {

  $("#" + form_id + "-note").html(''); // Zap any previous msg
  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-cost").html('');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');
  var str = $("#" + form_id).serialize();

  $.ajax({
    type: "POST",
    url: "/" + city + "/" + lang + "/ajax/get_freebie.php",
    data: str,
    dataType: 'json',
    success: function(response) {
      $("#" + form_id + "-note").ajaxComplete(function(event, request, settings) {

        if (response.status=="OK") {
          $("#" + form_id + "-quantity").html(response.quantity);
        }

        $("#" + form_id + "-progressbar").html('');
        // Don't re-display the button, they've either got it or they have no points
        // $("#" + form_id + "-button").css('display', 'block');
        $(this).html(response.msg);
      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Process a member's rating and comments on an offer; called from
 * popups/rate.php, which is in turn called from profile/purchases.php
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id the CSS ID of the calling form, from which the IDs of
 * @param offer_id OfferID used for loading FB feed dialogue
 * submit button, progress bar and note fields can be deduced
 */
function ratingSubmit(city, lang, form_id, offer_id) {

  $("#" + form_id + "-note").html(''); // Zap any previous msg
  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');
  var str = $("#" + form_id).serialize();
  $.ajax({
    type: "POST",
    url: "/" + city + "/" + lang + "/ajax/rate.php",
    data: str,
    success: function(msg){
      $("#" + form_id + "-note").ajaxComplete(function(event, request, settings){
        $("#" + form_id + "-progressbar").html('');
        $("#" + form_id + "-button").css('display', 'block');
        var resArr=msg.split('#'); // parse response from ajax for message and status: 'message#OK|FAIL'
        $(this).html(resArr[0]);
        //parent.window.location.href = parent.window.location.href;
        //parent.$.colorbox.close();
        if(resArr[1]=='OK' && offer_id) {
            var obj = {
                method: 'feed',
                link: 'http://limeandtonic.com/'+ city + '/' + lang + '/guide_deal.php?offer_id='+offer_id,
                display: 'iframe',
                redirect_uri: 'http://limeandtonic.com/'+ city + '/' + lang + '/fb-close.php'
            };
            //var fburl='http://www.facebook.com/dialog/feed?app_id='+app_id+'&link='+escape('http://limeandtonic.com/'+ city + '/' + lang + '/guide_deal.php?offer_id='+offer_id);
            $('#rate').html('<div>Thank You!</div>');
            //$('#rate').after('<iframe src="'+fburl+'" width="650" height="300"></iframe>');
            $('.fb_dialog_close_icon').live('click',function(){parent.window.location.href = parent.window.location.href;parent.$.colorbox.close()})
            $('input[name="cancel"]').live('click',function(){parent.window.location.href = parent.window.location.href;parent.$.colorbox.close()})
            FB.ui(obj, function(resp){parent.window.location.href = parent.window.location.href});
        } else {
            parent.window.location.href = parent.window.location.href;
            parent.$.colorbox.close();
        }

      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Registration of a new affiliate  Expects a
 * JSON response.
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id The CSS ID of the form.  Note the ID of the submit button
 * should be the same, with "-button" appended, and the ID where the progressbar
 * is displayed should use be the same, with "-progressbar" appended.
 * @return
 */
function register_affiliate(city, lang, form_id) {

  $("#" + form_id + "-button").css('display','none');
  $("#" + form_id + "-note").html('&nbsp;');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');

  var str = $("#" + form_id).serialize();
  $.ajax({
    type: "POST",
    url:  '/' + city + '/' + lang + '/ajax/register_affiliate.php',
    data: str,
    dataType: 'json',
    success: function(data) {
      $("#" + form_id + "-note").ajaxComplete(function(event, request, settings) {
        $("#" + form_id + "-progressbar").html('');
        if (data.status == 'OK') {
          // Prevent any previous msg from flashing up before the bounce
		  $("#" + form_id + "-note").attr("class", "normal");
          $("#" + form_id + "-note").html(data.msg);
		  $("#" + form_id + "-link").html(data.msg2);
        } else if (data.status == 'Failed') {
          $("#" + form_id + "-button").css('display','block');
          $("#" + form_id + "-note").attr("class", "errorMessage");
          $("#" + form_id + "-note").html(data.msg);
        }
      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Process a merchants rating and comments on a member; called from
 * popups/reverse_rate.php, which is in turn called from profile/merchants.php
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id the CSS ID of the calling form, from which the IDs of
 * submit button, progress bar and note fields can be deduced
 * @param yesno. A simple string with possible values Y or N
 *
 */
function reverseRatingSubmit(city, lang, form_id, yesno) {

  $("#" + form_id + "-note").html(''); // Zap any previous msg
  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');
  if (yesno == 'Y'){
	  $("#yes-no-buttons").html('<img src="/images/loading.gif" />');
  }

  var str = $("#" + form_id).serialize();
  $.ajax({
    type: "POST",
    url: "/" + city + "/" + lang + "/ajax/reverse_rate.php?yesno=" +yesno,
    data: str,
    success: function(msg){
      $("#" + form_id + "-note").ajaxComplete(function(event, request, settings){
        $("#" + form_id + "-progressbar").html('');
        $("#" + form_id + "-button").css('display', 'block');
        $(this).html(msg);
		if (yesno == 'Y'){
			$("#yes-no-buttons").html(msg);
		}
		if (msg == 'OK') {
			parent.$.colorbox.close();
		}
      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Merchant registration from register_merchant.php popup which is caled from live-v2/merchants.php.
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id The CSS ID of the form.  Note the ID of the submit button
 * should be the same, with "-button" appended, and the ID where the progressbar
 * is displayed should use be the same, with "-progressbar" appended.
 * @return
 */
function register_merchant(city, lang, form_id) {

  $("#" + form_id + "-note").html(''); // Zap any previous msg
  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');
  var str = $("#" + form_id).serialize();
  $.ajax({
    type: "POST",
    url:  '/' + city + '/' + lang + '/ajax/register-merchant.php',
    data: str,
    dataType: 'json',
    success: function(data) {
      $("#" + form_id + "-note").ajaxComplete(function(event, request, settings){
        $("#" + form_id + "-progressbar").html('');
		if (data.status == 'Failed') {
          $("#" + form_id + "-button").css('display','block');
          $("#" + form_id + "-note").html(data.msg);
        }
		if (data.status == 'OK') {
          $("#" + form_id + "-note").html(data.msg);
		  $("#" + form_id + "-button").css('display','none');

        }
      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Competition entry registration from register_comp_entry.php popup which is caled from competition/index.php.
 *
 * @param city The city the user is viewing, eg prague
 * @param lang The language selection the user is viewing, eg en
 * @param form_id The CSS ID of the form.  Note the ID of the submit button
 * should be the same, with "-button" appended, and the ID where the progressbar
 * is displayed should use be the same, with "-progressbar" appended.
 * @return
 */
function register_comp_entry(city, lang, form_id) {

  $("#" + form_id + "-note").html(''); // Zap any previous msg
  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');
  var str = $("#" + form_id).serialize();
  $.ajax({
    type: "POST",
	url: '/' + city + '/' + lang + '/ajax/add_hip_tip.php',
    data: str,
    dataType: 'json',
    success: function(data) {
      $("#" + form_id + "-note").ajaxComplete(function(event, request, settings){
        $("#" + form_id + "-progressbar").html('');
		if (data.status == 'OK') {
          $("#" + form_id + "-note").html(data.msg);
		  $("#" + form_id + "-button").css('display','none');
		  //parent.window.location.reload(true);

		  // Find the calling page (using parent)
          var p=parent.window.location.pathname.split('/');
          var dir=p[p.length-2];
          if (dir=='fbtabs') {
			  parent.window.location='../fbtabs/comp_thankyou.php';
		  } else {
			  parent.window.location='../competition/thankyou.php';
		  }
		  parent.$.colorbox.close();
        }
		if (data.status == 'Failed') {
          $("#" + form_id + "-button").css('display','block');
          $("#" + form_id + "-note").html(data.msg);
        }
      });
    }
  });
}

// --------------------------------------------------------------------
/**
 * Send SMS code to member's telephone number.  Called from the profile
 * index page.
 *
 */
function send_sms() {

    var phone_country_code=$("#phone_country_code").val();
    var mobile=$("#mobile").val();
    var pi_inprogress=$("#pi-inprogress");
    var sms_msg=$('#sms_msg');

    pi_inprogress.html('<img src="/images/loading.gif" />');

    $.ajax({
        type: "POST",
        url: "/" + city + "/" + lang + "/ajax/send-sms.php",
        dataType: 'json',
        data: {
            phone_country_code: phone_country_code,
            mobile: mobile
        },
        success: function(response) {
            // alert(response.status + "\n" + response.msg);
            pi_inprogress.html('');

            if (response.status=="OK") {
                if (sms_msg.hasClass('hidden')) {
                    sms_msg.removeClass('hidden');
                }
                sms_msg.html(response.msg);

                $('#send_sms').addClass('hidden');
                $('#verify_phone_form').slideDown('slow');

            } else {
                pi_inprogress.addClass('error');
                pi_inprogress.html(response.msg);
            }
        }
    });
}

// --------------------------------------------------------------------
/**
 * Verify an SMS code sent to member's phone.  Called from the profile
 * index page.
 *
 */
function verify_phone() {

    var sms_msg=$("#sms_msg");
    var send_sms=$('#send_sms');
    var sms_code=$("#sms_code");

    $.ajax({
        type: "POST",
        url: "/" + city + "/" + lang + "/ajax/update-profile.php",
        dataType: 'json',
        data: {
            sms_code: sms_code.val(),
            form: 'verify-phone'
        },
        success: function(response) {
            if (response.status=="OK") {
                // clean up display
                if (!send_sms.hasClass('hidden')) {
                    send_sms.addClass('hidden');
                }
                sms_msg.removeClass('error').html('OK!');

                $('#verify_phone_form').slideUp('slow', function() {
                    sms_msg.addClass('hidden').html('')
                    sms_code.val('');
                    // $('#verify-msg').html('');
                });
                $('#phone_status').html(response.msg);

                // And store the just-verified phone in the "old" hidden fields
                $('#old_phone_country_code').val($('#phone_country_code').val());
                $('#old_mobile').val($('#mobile').val());

            } else {
                sms_msg.removeClass('hidden').addClass('error').html(response.msg);
            }
        }
    });
}

// --------------------------------------------------------------------
/**
 * Find the value of the number displayed in the four boxes on the comp page and decrease by one
 *
 */
function decrease_counter() {

  if ($("#ones_div").html() != '0'){
	$("#ones_div").html($("#ones_div").html() - 1);
  } else {
	$("#ones_div").html('9');

	if ($("#tens_div").html() != '0'){
	  $("#tens_div").html($("#tens_div").html() - 1);
	} else {
	  $("#tens_div").html('9');

	  if ($("#hundreds_div").html() != '0'){
	    $("#hundreds_div").html($("#hundreds_div").html() - 1);
	  } else {
	    $("#hundreds_div").html('9');

		if ($("#thousands_div").html() != '0'){
	      $("#thousands_div").html($("#thousands_div").html() - 1);
	    }
	  }
	}
  }
}

// --------------------------------------------------------------------
/**
 * Updates a hiptip when a competition entrant adds more info to their HipTip
 *
 */
function hipTipCompUpdate(city, lang, form_id) {

  $("#" + form_id + "-note").html(''); // Zap any previous msg
  $("#" + form_id + "-button").css('display', 'none');
  $("#" + form_id + "-progressbar").html('<img src="/images/loading.gif" />');
  var str = $("#" + form_id).serialize();
  $.ajax({
    type: "POST",
    url:  '/' + city + '/' + lang + '/ajax/update-comp-hiptip.php',
    data: str,
    dataType: 'json',
    success: function(data) {
      $("#" + form_id + "-note").ajaxComplete(function(event, request, settings){
        $("#" + form_id + "-progressbar").html('');
		if (data.status == 'Failed') {
          $("#" + form_id + "-button").css('display','block');
          $("#" + form_id + "-note").html(data.msg);
        }
		if (data.status == 'OK') {
          $("#" + form_id + "-note").html(data.msg);
		  $("#" + form_id + "-button").css('display','none');
        }
      });
    }
  });
}


