var modal_stack=[];
var modal_index=0;
var base_url = "";
var  isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
var  isIE7 = /msie|MSIE 7/.test(navigator.userAgent);
var  isIE = /msie|MSIE [678]/.test(navigator.userAgent);

$(document).ready(function() {
gbu();
if(window != window.parent && window.parent.location.href.search("adm/preview") != -1) {
 $("#menu-2").hide();
 }
 ie  = /msie|MSIE [6]/.test(navigator.userAgent);
 if(ie) { 
  $(".menu-tab, .menu-tab-2, .menu-tab-clinic").hover(function() { 
   $(this).css('width',$(this).width());
   $(this).css('height',$(this).height());
   $(this).addClass('mtop') ;
   },function() {$(this).removeClass('mtop')});
  $(".quick_link_img").hover(
   function() {
   $(this).css("background", 'url("' + base_url + 'images/upload_test/smallgreenbg.gif") no-repeat');
   },
   function() {
   $(this).css("background", 'url("' + base_url + 'images/upload_test/smallbluebg.gif") no-repeat');
   } 
  );
  
}
 }
 );

function gbu() 
{
base_url = $("script[src*='/js/uk.js']").attr("src").replace("js/uk.js","");
return base_url;
}
/***
	 * Pacth for dialog-fix ckeditor problem [ by ticket #4727 ]
	 *      http://dev.jqueryui.com/ticket/4727
	 */
function fix_ck_dlg() {	
	$.extend($.ui.dialog.overlay, { create: function(dialog){
	        if (this.instances.length === 0) {
	                // prevent use of anchors and inputs
	                // we use a setTimeout in case the overlay is created from an
	                // event that we're going to be cancelling (see #2804)
	                setTimeout(function() {
	                        // handle $(el).dialog().dialog('close') (see #4065)
	                        if ($.ui.dialog.overlay.instances.length) {
	                                $(document).bind($.ui.dialog.overlay.events, function(event) {
	                                        var parentDialog = $(event.target).parents('.ui-dialog');
	                                        if (parentDialog.length > 0) {
	                                                var parentDialogZIndex = parentDialog.css('zIndex') || 0;
	                                                return parentDialogZIndex > $.ui.dialog.overlay.maxZ;
	                                        }
	                                       
	                                        var aboveOverlay = false;
	                                        $(event.target).parents().each(function() {
	                                                var currentZ = $(this).css('zIndex') || 0;
	                                                if (currentZ > $.ui.dialog.overlay.maxZ) {
	                                                        aboveOverlay = true;
	                                                        return;
	                                                }
	                                        });
	                                       
	                                        return aboveOverlay;
	                                });
	                        }
	                }, 1);
	               
	                // allow closing by pressing the escape key
	                $(document).bind('keydown.dialog-overlay', function(event) {
	                        (dialog.options.closeOnEscape && event.keyCode
	                                        && event.keyCode == $.ui.keyCode.ESCAPE && dialog.close(event));
	                });
	                       
	                // handle window resize
	                $(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize);
	        }
	       
	        var $el = $('<div></div>').appendTo(document.body)
	                .addClass('ui-widget-overlay').css({
	                width: this.width(),
	                height: this.height()
	        });
	       
	        (dialog.options.stackfix && $.fn.stackfix && $el.stackfix());
	       
	        this.instances.push($el);
	        return $el;
	}});
 }
(function($,window,undefined){
  '$:nomunge'; // Used by YUI compressor.
  
  // Reused string.
  var str_hashchange = 'hashchange',
    
    // Method / object references.
    doc = document,
    fake_onhashchange,
    special = $.event.special,
    
    // Does the browser support window.onhashchange? Note that IE8 running in
    // IE7 compatibility mode reports true for 'onhashchange' in window, even
    // though the event isn't supported, so also test document.documentMode.
    doc_mode = doc.documentMode,
    supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 );
  
  // Get location.hash (or what you'd expect location.hash to be) sans any
  // leading #. Thanks for making this necessary, Firefox!
  function get_fragment( url ) {
    url = url || location.href;
    return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
  };
  
  // Method: jQuery.fn.hashchange
  // 
  // Bind a handler to the window.onhashchange event or trigger all bound
  // window.onhashchange event handlers. This behavior is consistent with
  // jQuery's built-in event handlers.
  // 
  // Usage:
  // 
  // > jQuery(window).hashchange( [ handler ] );
  // 
  // Arguments:
  // 
  //  handler - (Function) Optional handler to be bound to the hashchange
  //    event. This is a "shortcut" for the more verbose form:
  //    jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
  //    all bound window.onhashchange event handlers will be triggered. This
  //    is a shortcut for the more verbose
  //    jQuery(window).trigger( 'hashchange' ). These forms are described in
  //    the <hashchange event> section.
  // 
  // Returns:
  // 
  //  (jQuery) The initial jQuery collection of elements.
  
  // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
  // $(elem).hashchange() for triggering, like jQuery does for built-in events.
  $.fn[ str_hashchange ] = function( fn ) {
    return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange );
  };
  
  
  $.fn[ str_hashchange ].delay = 50;
  /*
  $.fn[ str_hashchange ].domain = null;
  $.fn[ str_hashchange ].src = null;
  */
  
  special[ str_hashchange ] = $.extend( special[ str_hashchange ], {
    
    // Called only when the first 'hashchange' event is bound to window.
    setup: function() {
      // If window.onhashchange is supported natively, there's nothing to do..
      if ( supports_onhashchange ) {return false;}
      
      // Otherwise, we need to create our own. And we don't want to call this
      // until the user binds to the event, just in case they never do, since it
      // will create a polling loop and possibly even a hidden Iframe.
      $( fake_onhashchange.start );
    },
    
    // Called only when the last 'hashchange' event is unbound from window.
    teardown: function() {
      // If window.onhashchange is supported natively, there's nothing to do..
      if ( supports_onhashchange ) {return false;}
      
      // Otherwise, we need to stop ours (if possible).
      $( fake_onhashchange.stop );
    }
    
  });
  
  // fake_onhashchange does all the work of triggering the window.onhashchange
  // event for browsers that don't natively support it, including creating a
  // polling loop to watch for hash changes and in IE 6/7 creating a hidden
  // Iframe to enable back and forward.
  fake_onhashchange = (function(){
    var self = {},
      timeout_id,
      
      // Remember the initial hash so it doesn't get triggered immediately.
      last_hash = get_fragment(),
      
      fn_retval = function(val){return val;},
      history_set = fn_retval,
      history_get = fn_retval;
    
    // Start the polling loop.
    self.start = function() {
      timeout_id || poll();
    };
    
    // Stop the polling loop.
    self.stop = function() {
      timeout_id && clearTimeout( timeout_id );
      timeout_id = undefined;
    };
    
    // This polling loop checks every $.fn.hashchange.delay milliseconds to see
    // if location.hash has changed, and triggers the 'hashchange' event on
    // window when necessary.
    function poll() {
      var hash = get_fragment(),
        history_hash = history_get( last_hash );
      
      if ( hash !== last_hash ) {
        history_set( last_hash = hash, history_hash );
        
        $(window).trigger( str_hashchange );
        
      } else if ( history_hash !== last_hash ) {
        location.href = location.href.replace( /#.*/, '' ) + history_hash;
      }
      
      timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay );
    };
    
    // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
    // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    $.browser.msie && !supports_onhashchange && (function(){
      // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
      // when running in "IE7 compatibility" mode.
      
      var iframe,
        iframe_src;
      
      // When the event is bound and polling starts in IE 6/7, create a hidden
      // Iframe for history handling.
      self.start = function(){
        if ( !iframe ) {
          iframe_src = $.fn[ str_hashchange ].src;
          iframe_src = iframe_src && iframe_src + get_fragment();
          
          // Create hidden Iframe. Attempt to make Iframe as hidden as possible
          // by using techniques from http://www.paciellogroup.com/blog/?p=604.
          iframe = $('<iframe tabindex="-1" title="empty"/>').hide()
            
            // When Iframe has completely loaded, initialize the history and
            // start polling.
            .one( 'load', function(){
              iframe_src || history_set( get_fragment() );
              poll();
            })
            
            // Load Iframe src if specified, otherwise nothing.
            .attr( 'src', iframe_src || 'javascript:0' )
            
            // Append Iframe after the end of the body to prevent unnecessary
            // initial page scrolling (yes, this works).
            .insertAfter( 'body' )[0].contentWindow;
          
          // Whenever `document.title` changes, update the Iframe's title to
          // prettify the back/next history menu entries. Since IE sometimes
          // errors with "Unspecified error" the very first time this is set
          // (yes, very useful) wrap this with a try/catch block.
          doc.onpropertychange = function(){
            try {
              if ( event.propertyName === 'title' ) {
                iframe.document.title = doc.title;
              }
            } catch(e) {}
          };
          
        }
      };
      
      // Override the "stop" method since an IE6/7 Iframe was created. Even
      // if there are no longer any bound event handlers, the polling loop
      // is still necessary for back/next to work at all!
      self.stop = fn_retval;
      
      // Get history by looking at the hidden Iframe's location.hash.
      history_get = function() {
        return get_fragment( iframe.location.href );
      };
      
      // Set a new history item by opening and then closing the Iframe
      // document, *then* setting its location.hash. If document.domain has
      // been set, update that as well.
      history_set = function( hash, history_hash ) {
        var iframe_doc = iframe.document,
          domain = $.fn[ str_hashchange ].domain;
        
        if ( hash !== history_hash ) {
          // Update Iframe with any initial `document.title` that might be set.
          iframe_doc.title = doc.title;
          
          // Opening the Iframe's document after it has been closed is what
          // actually adds a history entry.
          iframe_doc.open();
          
          // Set document.domain for the Iframe document as well, if necessary.
          domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' );
          
          iframe_doc.close();
          
          // Update the Iframe's hash, for great justice.
          iframe.location.hash = hash;
        }
      };
      
    })();
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    
    return self;
  })();
  
})(jQuery,this);


//************** Code for gmap starts *************** //		
 
function makeMap(id,zoom){

        
        var str = $("#" + id + "-gmap").val();
        var dt = str.split("|");
        var latitude  = dt[0];
        var longitude = dt[1];
        
        address = dt[2];
        
        if((latitude > 0.0001 || latitude < -0.0001) && latitude!="" && longitude!=""){
            var center = new google.maps.LatLng(latitude,longitude);
             var myOptions = {
	      zoom: zoom,
      	      center: center,
      	      mapTypeId: google.maps.MapTypeId.ROADMAP
    	     }   
            var map = new google.maps.Map($("#" + id).get(0),myOptions); 
//            setTimeout(function() {
             var marker = new google.maps.Marker({map:map, position:center });
//             },1500);
        }
        else
        {
            showAddress(address,id,zoom);
        }
		
}

function zip2city(address,succ_func,err_func)	
{
var geocoder =  new google.maps.Geocoder();
//var address = "" + zip + ",UK";
geocoder.geocode( {'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
       succ_func(results[0]);
       }
       else {
       err_func(status);
       }
 });
}

function showAddress(address,id,zoom) {
    var myOptions = {
      zoom: zoom,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map($("#" + id).get(0),myOptions);
//    map.addControl(new GSmallMapControl());
    geocoder =  new google.maps.Geocoder();
    
//alert(address);
geocoder.geocode( {'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map, 
            position: results[0].geometry.location
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });

}
	
//************** Code for gmap ends *************** //		
	
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}



function sget(strUrl)
{
    var strReturn = "";

    jQuery.ajax({
        url:strUrl ,
        success:function(html){
            strReturn = html;
        },
        error:function(jqxhr) {
            alert("Failed to load " + strUrl +'\n' + jqxhr.responseText);
        },
        async:false
    });
    return strReturn;
}
function aget(strUrl)
{
    var strReturn = "";

    jQuery.ajax({
        url:strUrl ,
        success:function(html){
            strReturn = html;
        },
        error:function(strUrl) {
            alert("Failed to load " + strUrl);
        },
        async:true
    });
    return strReturn;
}

function dlg_close(event,ui){
if(modal_index >2) {
 var h = modal_stack[modal_index-1];
 location.hash = h;
 modal_index--;
 } else {
 location.hash = "";
 modal_index =0;
 }
}

function show_login(url)
{
    var login_box;
    if($("#login-wrapper").length) $("#login-wrapper").remove();

    modal_stack[modal_index++] = "#login-wrapper";
    location.hash = "#login-wrapper";
    login_box = sget(url + "login/dlg/login/" + Math.random());
    $("body").append(login_box);
    $("#login-wrapper").dialog({
        modal: true,
        close:dlg_close,
	width:350,
	open: function(event, ui) {
         $("#lfield").focus();
        if(isIE6 || isIE7)
	 $("#login-wrapper").prev().attr('class','sigur').html('');;	
         }
    });
if(!$.browser.msie) {
 var muiegoogle = $(window).scrollTop();
 setTimeout("$(window).scrollTop(" + muiegoogle + ")",4);
 }
return false;
}


function do_ac()
{
    var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
    if($("#clinic_name").val().length == 0) {
        $("#clinic_msg").html("Clinic name is required");
        $("#clinic_name").focus();
        return;
    }

       if($("#branch_address1").val().length == 0) {
        $("#clinic_msg").html("Clinic address1 required");
        $("#branch_address1").focus();
        return;
    }
    if($("#branch_zip").val().length == 0) {
        $("#clinic_msg").html("Postcode required");
        $("#branch_zip").focus();
        return;
    } 


      if($("#branch_phone").val().length == 0) {
        $("#clinic_msg").html("Phone number required");
        $("#branch_phone").focus();
        return;
    }

    if($("#contact_name").val().length == 0) {
        $("#clinic_msg").html("Contact name is required");
        $("#contact_name").focus();
        return;
    }

    if($("#clinic_email").val().search(emailRegEx)  == -1 ) {
        $("#clinic_msg").html("Valid email address is required");
        $("#clinic_email").focus();
        return;
    }

    if($("#password").val().length  < 3 ) {
        $("#clinic_msg").html("Password length should be at least 3 characters");
        $("#password").focus();
        return;
    }
   if($("#clinic_name").val()[0] != "*")
    if($("#password").val() != $("#passwordc").val() ) {
        $("#clinic_msg").html("Password confirmation error");
        $("#passwordc").focus();
        return;
    }
    if( !$("#qform_terms").attr("checked")) {
        $("#clinic_msg").html("Please agree with terms and conditions");
        $("#qform_terms").focus();
        return;
    }
   $("#save").val($("#clinic_email").val().length * 7);

    if($("#clinic_country").val() == 1) {
      var addr  = /* $("#branch_address1").val() + "," +*/ $("#branch_zip").val() + ",UK";
      $("#clinic_msg").text("checking..");  
    $("#register").addClass('op2');
    var ct=zip2city(addr,
    function(r) {
     if(!$("#branch_city").val().length) 
       $("#branch_city").val(r.address_components[2].long_name);
      $("#branch_latitude").val(r.geometry.location.lat());
      $("#branch_longitude").val(r.geometry.location.lng());
      $("#clinic_msg").text("ok");
      $("#register").removeClass('op2');
      register_finish();
    },
    function(status) {
     $("#clinic_msg").text("geocoder unsuccesful: "+status);
     $("#register").removeClass('op2');
     register_finish();
     });
   } 
  else register_finish();
 //$("#register").submit();
}

var r_no_go = 0;
function register_finish()
{
    if(r_no_go) return;
    r_no_go = 1;
    $("#do_acx").hide();
    url = $("#register").attr('action');
    data = $("#register").serialize();
    jQuery.post(url,data,ac_done) ;
}

function show_ac(url)
{
    var ac_box;
    modal_stack[modal_index++] = "#ac-wrapper";
    location.hash = "#ac-wrapper";
    if($("#ac-wrapper").length) $("#ac-wrapper").remove();

    ac_box = sget(url + "login/dlg/ac/" + Math.random());
    $("body").append(ac_box);
    $("#ac-wrapper").dialog({
        modal: true,
        show:'slide',
        width:800
    });
}

function show_lg(url,what)
{
    var legal_box;
    var htt=600;
    modal_stack[modal_index++] = '#legal-wrapper';
 if($("#crap_iframe").length) {
  var ppp=1;
  htt = 450; 
   } else
    location.hash = '#legal-wrapper';
    if($("#legal-wrapper").length) $("#legal-wrapper").remove();

    legal_box = sget(url + "login/dlg/" + what + "/" + Math.random());
    $("body").append(legal_box);
    $("#legal-wrapper").dialog({
        modal: true,
	open: function() {
     	$("#legal-wrapper").prev("div").removeClass("ui-widget-header").html(
	    '<img src="' + url+ 'images/close.jpg" alt="close" style="float: right;cursor: pointer;" id="close_form" onclick="$(\'#legal-wrapper\').dialog(\'close\');"/>'
	)},
        width:600,
        height:htt,
        closeOnEscape:false
    });
    $("#legal-wrapper").bind("click",function() {
        $("#legal-wrapper").dialog("close");
	 });
 $("#legal-wrapper").keydown(function(e) {
 if(e.which == 27)  {
     $("#legal-wrapper").dialog("close");  
      return false;
     }
    });
    $("#legal-wrapper").focus();
}
function do_login(url)
{
    $("#login_message").text("Logging in...");
    url = $("#login_form").attr('action');
    data = $("#login_form").serialize();
    jQuery.post(url,data,login_done) ;

}
function login_done(msg,result,obj)
{
    var rs;
    if(result == "success") {
        rs = msg.split("|");
        if(rs[0] == "0") {
            window.location = rs[1];
        } else {
            $("#login_message").html(rs[1]);
            if(rs[0] == 2) {
                $("#login_row").slideToggle(400);
                $("#login_button").val("Close");
                $("#login_button").removeAttr("onclick");
                $("#login_button").bind("click",function() {
                    $("#login-wrapper").dialog("close");
                    return false;
                });
            }
        }
    } else {
        alert("something failed");
    }
}

function ac_done(msg,result,obj)
{
    var rs;
    r_no_go = 0;
    if(result == "success") {
        rs = msg.split("|");
        if(rs[0] == "0") {
            window.location = rs[1];
        } else {
            $("#clinic_msg").html(rs[1]);
            if(rs[0] == 2 && $("#clinic_name").val()[0] != "*") {
		$("#do_acx").show();

                $("#do_acx").val("Back");
                $("#do_acx").removeAttr("onclick");
	 	$("#tform").remove();	
                $("#do_acx").bind("click",function() {
                    history.go(-1);
                    return false;
                });
            }
        }
    } else {
        $("#do_acx").show();

        alert("something failed");
    }
}

function forgot_password(url)
{
    $("#login_message").text("Forgot password?");
//    $("#pass_row").slideToggle(400);
 $("#pass_row").hide();
    $("#login-wrapper").dialog("option","title","Forgot password");
    $("#login-wrapper").dialog("option","title","Forgot password");
    $("#forgot_password").hide();
    $("#login_button").text("Send");
    $("#is_login").val(0);
}

function logout(url)
{
window.location = url + "login/logout";
}

 $(document).ready(function(){
// alert(location.hash);
if(!isIE6) 
 $(window).hashchange( function(){
 if(modal_index > 0 ) {
  modal = modal_stack[modal_index -1];
//  alert(modal + " " + location.hash);
 } else modal = "";
 if($(modal).length && location.hash != modal) {
  
  $(modal).dialog("close");
  modal_index--;
  if(modal_index <=0) {modal_index=0;location.hash="";}
   else {
  location.hash = modal_stack[modal_index-1];
    }
 }
})
});

function delete_image()
{
var bu = $("#base_url").val();
var iid = $("#img-id").val();
if(!confirm("Delete image " + iid + "?")) return;
sget(bu + "adm/dphoto/" + iid + "/" + Math.random());
window.location = window.location;
}

function img_common_init()
{
    $(".thmb").bind("click",function() {
        var ix = $(this).attr("pid");
        Galleria.get()[0].show(ix)
        $(".tc").css("border","1px solid #f0f0f0");
        $("#thmb-" + ix).parent().removeClass('op');
 
    });
//    $("#jaful").sortable();
    $(".tc").hover(
     function(){
        $(this).removeClass('op');
    },
     function(){
      if($(this).attr("pid") != Galleria.get()[0].getIndex())
        $(this).addClass('op');
    }
    )
}
function save_order()
{
var cons = $(".tc");
var p="";
for(var i=0;i<cons.length;i++) {
 if(p.length) p += ";";
 p +=  $(cons[i]).attr("zid") ;
 }
$("#the_order").val(p);
var data = $("#sort_order").serialize();
var url = $("#base_url").val() + "adm/photos";
jQuery.post(url,data,function(msg,code,obj) {
 $("#ssort").hide();  
 });
}

function ck_photo_input()
{
if($("#image_caption").val().length < 4) {
 $("#img-msg").text("Please add a longer image caption");
 return false;
 }
if($("#image_file").val().search(/\.jpg$|\.png$|\.gif$/i) ==  -1) {
 $("#img-msg").text("Please add a valid image file .jpg | .png | .gif");
 return false;
 }
}
function cktest_save()
{
    var editor = $('#editck1').ckeditorGet();
    alert( $('#editck1').val());
    alert(editor.getData());
}
function save_clinic_about(id)
{
   var dom_id = "#ck-" + id;
   var fid = "#f" + id;
  if(id > 1) {
   var editor = $(dom_id).ckeditorGet();
   editor.resetDirty();
   }
   var data = $(fid).serialize();
   var url =  $("#base_url").val() + "adm/about";
   $(dom_id).parent().addClass('op2');
  jQuery.post(url,data,function(msg,code,obj) {
   $(dom_id).parent().removeClass('op2');
   });

  }
function trt_clicked(idx)
{
var me = $("#xtr-" + idx);
var mec = me.attr("checked");
 $("#"+me.parent().parent().parent().parent().parent().parent().attr("id").replace("form-","svd-")).text(" not saved");
if(mec) {
 me.parent().next("td").show();
 me.parent().next("td").next("td").show();
 } else {
 me.parent().next("td").hide();
 me.parent().next("td").next("td").hide();
 }
}

function save_tr_page(pid)
{
var fid = "#form-" + pid;
var svd = "#svd-" + pid;
var url = $(fid).attr("action");
var data = $(fid).serialize();
$(fid).parent().addClass('op2');
  jQuery.post(url,data,function(msg,code,obj) {
   $(fid).parent().removeClass('op2');
   $(svd).text(" Saved!");
//alert(msg);
   });
}

function delete_staff(idx)
{
if(confirm("Delete " +  $("#as-" +idx).text() + " ?")) {
 var url= $("#base_url").val() + "adm/delete_staff/" + idx + "/" + Math.random();
 sget(url);
 location.reload(true);
 }

}

function load_staff(idx)
{
var url = $("#base_url").val() + "adm/load_staff/" + idx + "/" + Math.random();
$("#staffc-l").load(url);
$("a","#staffc-r").css("font-weight","normal");
$("#as-" + idx).css("font-weight","bold");
}


function save_staff()
{

if($("input[name='staff_name']").val().length == 0) {
 $("#staff_msg").html("Please fill in doc's name");
 $("input[name='staff_name']").focus();
 return;
 }

if($("textarea[name='staff_qualification']").val().length == 0) {
 $("#staff_msg").html("Please fill in doctor's qualifications");
 $("textarea[name='staff_qualification']").focus();
 return;
 }
if($("textarea[name='staff_experience']").val().length == 0) {
 $("#staff_msg").html("Please fill in doctor's experience");
 $("textarea[name='staff_experience']").focus();
 return;
 }
$("#edit_staff").submit();
}

function load_branch(idx)
{
var url = $("#base_url").val() + "adm/load_branch/" + idx + "/" + Math.random();
$("roundrect").remove();
$("#branchc").load(url,function(msg,st,obj) {

 makeMap("the-map",14);
});
$("a","#branch-b").css("font-weight","normal");
$("#ab-" + idx).css("font-weight","bold");
}

function save_branch()
{

if($("input[name='branch_name']").val().length == 0) {
 $("#clinic_msg").html("Please fill in branch name");
 $("input[name='branch_name']").focus();
 return;
 }
if($("input[name='branch_phone']").val().length == 0) {
 $("#clinic_msg").html("Please fill in branch phone #");
 $("input[name='branch_phone']").focus();
 return;
 }
if($("input[name='branch_address1']").val().length == 0) {
 $("#clinic_msg").html("Please fill in branch address 1#");
 $("input[name='branch_address1']").focus();
 return;
 }
if($("input[name='branch_city']").val().length == 0) {
 $("#clinic_msg").html("Please fill in branch city");
 $("input[name='branch_city']").focus();
 return;
 }
if($("input[name='branch_zip']").val().length == 0) {
 $("#clinic_msg").html("Please fill in branch zip");
 $("input[name='branch_zip']").focus();
 return;
 }
  if($("#branch_country_id").val() == "1") {
   $("#clinic_msg").text("checking..");
   var addr =/*$("#branch_address1").val() +*/ "," + /* $("#branch_city").val() +*/ "," + $("#branch_zip").val() + ",UK";
   $("#edit_branch").addClass("op2");
    var ct=zip2city(addr,
    function(r) {
     if(!$("#branch_city").val().length) 
       $("#branch_city").val(r.address_components[2].long_name);
      $("#branch_lat").val(r.geometry.location.lat());
      $("#branch_long").val(r.geometry.location.lng());
      $("#clinic_msg").text("ok");
      $("#edit_branch").removeClass('op2');
      $("#edit_branch").submit();
    },
    function(status) {
     $("#clinic_msg").text("geocoder unsuccesful: "+status);
     $("#edit_branch").removeClass('op2');
     });
  }
else $("#edit_branch").submit();
}

function delete_branch(idx)
{
if(confirm("Delete " +  $("#ab-" +idx).text() + " ?")) {
 var url= $("#base_url").val() + "adm/delete_branch/" + idx + "/" + Math.random();
 sget(url);
 location.reload(true);
 }

}
function delete_deal(idx)
{
if(confirm("Delete " +  $("#ab-" +idx).text() + " ?")) {
 var url= $("#base_url").val() + "adm/delete_deal/" + idx + "/" + Math.random();
 sget(url);
 location.reload(true);
 }

}

function change_password()
{
var cp = $("input[name='current_pass']");
var np = $("input[name='new_pass']");
var npc = $("input[name='confirm_pass']");
if(cp.val().length < 3) {
  $("#clinic_msg").html("Type your old password");
  cp.focus();return;
  }
if(np.val().length < 3) {
  $("#clinic_msg").html("New password is too short. (Min 3 characters)");
  np.focus();
 return;
 }
if(np.val() != npc.val()) {
  $("#clinic_msg").html("Password confirmation is wrong");
  npc.focus();
 return;
 }
    url = $("#change_pass").attr('action');
    data = $("#change_pass").serialize();
    jQuery.post(url,data,function(msg,code,obj) {
    $("#clinic_msg").text(msg);
     }) ;
}

function save_settings()
{
var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
var cn = $("input[name='clinic_name']");
var ce = $("input[name='clinic_contact_email']");
var un = $("input[name='user_name']");
var ue = $("input[name='user_email']");
var cp = $("input[name='clinic_phone1']");
if(!cn.val().length) {
 $("#clinic_msg").text("Clinic name is too short");
 cn.focus();return;
 }
if(!un.val().length) {
 $("#clinic_msg").text("User name is too short");
 un.focus();return;
 }
if(!ue.val().length) {
 $("#clinic_msg").text("User email is too short");
 ue.focus();return;
 }
if(!ce.val().length) {
 $("#clinic_msg").text("Clinic email is too short");
 ue.focus();return;
 }
if(ue.val().search(emailRegEx)  == -1 ) {
 $("#clinic_msg").html("Valid email address is required");
 ue.focus();
 return;
}
if(!cp.val().length) {
 $("#clinic_msg").text("Clinic phone is too short");
 cp.focus();return;
 }
    url = $("#edit_settings").attr('action');
    data = $("#edit_settings").serialize();
    jQuery.post(url,data,function(msg,code,obj) {
    $("#clinic_msg").text(msg);
     }) ;
}







function delete_tmonial(idx)
{
if(confirm("Delete " +  $("#ab-" +idx).text() + " ?")) {
 var url= $("#base_url").val() + "adm/delete_reviewst/" + idx + "/" + Math.random();
 sget(url);
 location.reload(true);
 }

}

function load_tmonial(idx)
{
var url = $("#base_url").val() + "adm/load_reviewst/" + idx + "/" + Math.random();
$("#tmonial-form").load(url);
$("a","#tmonial-list").css("font-weight","normal");
$("#ab-" + idx).css("font-weight","bold");
}


function save_tmonial()
{

if($("input[name='review_submitted_by']").val().length == 0) {
 $("#review_msg").html("Please fill patient's name");
 $("input[name='review_submitted_by']").focus();
 return;
 }
if($("input[name='review_tname']").val().length == 0) {
 $("#review_msg").html("Enter treatment's name");
 $("input[name='review_tname']").focus();
 return;
 }
if($("input[name='review_title']").val().length == 0) {
 $("#review_msg").html("Enter testimonial's title");
 $("input[name='review_title']").focus();
 return;
 }

if($("textarea[name='review_comment']").val().length == 0) {
 $("#tmonial_msg").html("Fill in the testimonial text");
 $("textarea[name='review_comment']").focus();
 return;
 }

$("#tmonials").submit();
}

function review_dates()
{
var url=$("#base_url").val() + "adm/review_list/";
var d1=$("input[name='review_date_min']").val();
var d2=$("input[name='review_date_max']").val();
url +=d1.replace(/\//g,"-") + "/" + d2.replace(/\//g,"-") + "/" + Math.random();;
$("#landr").load(url);
}

function load_review(idx)
{
var url = $("#base_url").val() + "adm/load_review/" + idx + "/" + Math.random();
$("#rv1").load(url);
$("a","#review_list").css("font-weight","normal");
$("#ab-" + idx).css("font-weight","bold");
}

function post_review_reply()
{
   if($("#rpltext").val().length < 5) {
    alert("Please enter a longer reply");
    $("#rpltext").focus();
     return;
     }
    url = $("#post_reply").attr('action');
    data = $("#post_reply").serialize();
    jQuery.post(url,data,function(msg,code,obj) {
    load_review($("#review_id").val());
    }) ;
}



function xxxqform(clinic_id,form_id)
{
var url = $("#qf_url").val() + "gf/" + clinic_id + "/" + form_id + "/" + Math.random();
var html = sget(url);


if($("#qform_qform").length) {
 $("#qform_qform").remove();
 }
 html = "<div id='qform_qform'>" + html + "</div>";

 $("body").append(html);
 var wiwi = $("#qform_qform div:first").css("width");
// var kiki = $("#qform_qform style:first").html();
// alert(kiki);
// $("textarea[name='lead_enquiry']").val("");

 $("#qform_qform").dialog({
  width:wiwi,height:'auto',
  modal:true,
  postition:'center',
  open:function() { 
  $("input[name='lead_name']").focus(); 
  $("textarea[name='lead_enquiry']").css("overflow","hidden");
  $("#bform_close").click(function() {
    $("#qform_qform").dialog("close");
    $("#qform_qform").dialog("destroy");
    $("#qform_qform").remove();return false;
    });
  $("#bform_policy").click(function() {
    show_lg($("#qf_url").val(),"p");return false;
    });
   $("#bform_terms").click(function() {
    show_lg($("#qf_url").val(),"t");return false;
    });
  }
  });
 if($("[name='qsubmit']","#qform_qform").length) {
  $("[name='qsubmit']","#qform_qform").bind("click",save_qform);
  }
}

function isValidPostcode(p) {
	var postcodeRegEx = /[A-Z]{1,2}[0-9A-Z]{1,2} ?[0-9][A-Z]{2}/i;
	return postcodeRegEx.test(p);
}
function save_qform()
{
var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
var qform = $(this).parents("form");
$("#qform_message").text("\u00A0"); 
//console.log(qform);
if(!qform.length) {
 alert("Something is bad with the form");
 return;
 }
var qname = qform.find("input[name='lead_name']");
var qfname = qform.find("input[name='lead_fname']");
var qtitle = qform.find("select[name='lead_title']");
var qemail = qform.find("input[name='lead_email']");
var qphone = qform.find("input[name='lead_phone']");
var qtreat = qform.find("input[name='lead_treatment']");
var qcity = qform.find("input[name='lead_city']");
var qzip = qform.find("input[name='lead_postcode']");
var qaddress1 = qform.find("input[name='lead_address1']");
var qaddress2 = qform.find("input[name='lead_address2']");
var qinfo = qform.find("textarea[name='lead_enquiry']");
var qsubmit = qform.find("input[name='qsubmit']");
var qterms = qform.find("input[name='qform_terms']");

var title,name,val,hh,i
var inputs = qform.find("input,select");
if(qfname.length) {
 if(!qfname.val().length) {
  $("#qform_message").text("First name is required");
  qfname.focus();
  return;
  }
 }

if(qname.length) {
 if(!qname.val().length) {
 if(qname.attr("error"))  $("#qform_message").text(qname.attr("error"));else 
  $("#qform_message").text("Name is required");
  qname.focus();
  return;
  }
 }

if(qtreat.treat) {
 if(!qtreat.val().length) {
  $("#qform_message").text("Treatment name is required");
  qtreat.focus();
  return;
  }
 }


if(qaddress1.length) {
 if(!qaddress1.val().length) {
  $("#qform_message").text("This address field is required");
  qaddress1.focus();
  return;
  }
 }
if(qaddress2.length) {
 if(!qaddress2.val().length) {
  $("#qform_message").text("Secondary address field is required");
  qaddress2.focus();
  return;
  }
 }
if(qcity.length) {
 if(!qcity.val().length) {
  $("#qform_message").text("City is required");
  qcity.focus();
  return;
  }
 }
if(qzip.length) {
 if(!isValidPostcode(qzip.val())) {
  $("#qform_message").text("Valid UK postcode required");
  qzip.focus();
  return;
  }
 }



if(qphone.length) {
 if(!qphone.val().length) {
  $("#qform_message").text("Phone number is required");
   qphone.focus();
   return;
  }
 }
if(qemail.length) {
if(qemail.val().search(emailRegEx)  == -1 ) {
 $("#qform_message").text("Valid email address is required");
 qemail.focus();
 return;
 }
}
if(qinfo.length) {
 if(qinfo.val().length < 1) {
  $("#qform_message").text("Please enter your enquiry");
   qinfo.focus();
   return;
  }
 } 
if(qterms.length) {
 if(!qterms.attr("checked")) {
  $("#qform_message").text("Please agree with terms of use");
  qterms.focus();return;
  }
 }
for( i=0;i<inputs.length;i++) {
 if($(inputs[i]).attr("r")) {

  title = $(inputs[i]).attr("title");
  name = $(inputs[i]).attr("name"); 
  val = $(inputs[i]).val();
  if(val.length == 0) {
   if(title != undefined) hh = title;else hh = name;
   $("#qform_message").text(hh + " is required");
   $(inputs[i]).focus();
   return;
   } 
  }
 }
 var url = $("#qf_url").val() + "/qsf";
 var data = qform.serialize();  
 var qfname =  qform.attr("name");
 var cname = qform.find("h2 > span").text();
 qsubmit.hide();

    jQuery.post(url,data,function(msg,code,obj) {
    if($("#qform_qform").length) {
     $("#qform_qform").dialog("close");
     $("#qform_qform").dialog("destroy");
     $("#qform_qform").remove();
     }
     jqalert(msg);
    _gaq.push(['_trackEvent', 'forms', 'submit', cname + '___' + qfname ]);
qsubmit.show();
    }) ;

}
function jqalert(message,jeg)
{
var ww = 'auto';
if(isIE6) ww = 350;
if(! $("#jqalert").length) {
 $("body").append("<div title='Treatment Saver' id='jqalert'></div>");
 }
$("#jqalert").html(message);
$("#jqalert").dialog({height:'auto',width:ww,modal:true,buttons: {"Ok": function() {if(jeg) eval(jeg);$(this).dialog("close");}}});
}


function load_enquiry(idx)
{
var url = $("#base_url").val() + "adm/load_enquiry/" + idx + "/" + Math.random();
$("#enquiry_form").load(url);
$("a","#review_list").css("font-weight","normal");
$("#ab-" + idx).css("font-weight","bold");
}

function save_enquiry()
{
if($("textarea[name='lead_comment']").val().length < 2) {
 $("#quote_msg").html("Please fill in some comment");
 $("textarea[name='lead_comment']").focus();
 return;
 }
    url = $("#edit_quote").attr('action');
    data = $("#edit_quote").serialize();
    jQuery.post(url,data,function(msg,code,obj) {
    $("#quote_msg").text(msg);
    $("#qfsave").remove();
     }) ;
}

function ck_toolbars(how)
{

if(!how) return [
    ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList','-' ,'Undo','Redo'],
    ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock']
];
return [
    ['Source','-','Save','NewPage','Preview','-','Templates'],
    ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
    ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
    ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'],
    '/',
    ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
    ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'],
    ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
    ['BidiLtr', 'BidiRtl'],
    ['Link','Unlink','Anchor'],
    ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe'],
    '/',
    ['Styles','Format','Font','FontSize'],
    ['TextColor','BGColor'],
    ['Maximize', 'ShowBlocks','-','About']
];
}
function nl2br(str)
{
return str.replace(/\n/,"<br/>");
}

function preview_deal(level)
{
$("#is_preview").val(level);
 url = $("#dealform").attr('action');
 data = $("#dealform").serialize();
 jQuery.post(url,data,function(msg,code,obj) {
    jqalert(msg);
    if($("#until_id").length) {
     do_count("#counter","#until_id");
     $(".calendar").css("background-image","none");
     }
    //location.reload(true);   
 })
}
function save_deal()
{
 var dp = $("input[name='deal_price']").val();
 var deal_id = $("input[name='deal_id']").val();
 var lp =  $("input[name='deal_list_price']").val();
 $("#is_preview").val(0);

if(parseFloat(lp) !=lp || parseFloat(dp) !=dp) {
 $("#cdeal_msg").text("One of the prices is not a number");
 $("input[name='deal_price']").focus();
 return;
 }
if(parseFloat(dp) >= parseFloat(lp)) {
 $("#cdeal_msg").text("deal price should pe lower than list price");
 $("input[name='deal_price']").focus();
 return; 
 }
if($("textarea[name='deal_sdesc']").val().length < 4) {
 $("#cdeal_msg").text("Short description is too short!");
 $("textarea[name='deal_sdesc']").focus();
 return;
 }
if($("textarea[name='deal_description']").val().length < 4) {
 $("#cdeal_msg").text("Description is too short!");
 $("textarea[name='deal_description']").focus();
return;
 }
is_admin = $("input[name='deal_enabled']").length;
if(is_admin) {
  // do some more checks
 }
 url = $("#dealform").attr('action');
 data = $("#dealform").serialize();
 jQuery.post(url,data,function(msg,code,obj) {
    if(!is_admin) jqalert(msg); else alert(msg);
    if(deal_id==-1 && is_admin) location.reload(true);   
 }) ;
}


function dp_init() 
{
var ccs = $("#base_url").val() + "css/uk.css";
is_admin = $("input[name='deal_enabled']").length;
var tbx = ck_toolbars(is_admin);


if(is_admin) {
 $("textarea[name='deal_fineprint']").ckeditor({toolbar:tbx,height:150, enterMode : CKEDITOR.ENTER_BR/*,contentsCss:ccs*/});
 $("textarea[name='deal_description']").ckeditor({toolbar:tbx,height:150, enterMode : CKEDITOR.ENTER_BR/*,contentsCss:ccs*/});
 $("textarea[name='deal_email']").ckeditor({toolbar:tbx,height:150, enterMode : CKEDITOR.ENTER_BR/*,contentsCss:ccs*/});
 $("textarea[name='deal_email_clinic']").ckeditor({toolbar:tbx,height:150, enterMode : CKEDITOR.ENTER_BR/*,contentsCss:ccs*/});
 $("textarea[name='deal_highlights']").ckeditor({toolbar:tbx,height:150, enterMode : CKEDITOR.ENTER_BR/*,contentsCss:ccs*/});
 $("input[name='deal_start_date']").datepicker({
 dateFormat:"dd/mm/yy"
 });

 $("input[name='deal_start_date']").bind("focus",function() { 
 $(".ui-widget-header","#ui-datepicker-div").removeClass("ui-widget-header").addClass("ui-widget-header-orig");
 });


 $("input[name='deal_end_date']").datepicker({dateFormat:"dd/mm/yy"});
 }
 $("input[name='deal_end_date']").bind("focus",function() { 
 $(".ui-widget-header","#ui-datepicker-div").removeClass("ui-widget-header").addClass("ui-widget-header-orig");
 });
$("input[name='deal_price'],input[name='deal_list_price']").keyup(function() {
 var dp = $("input[name='deal_price']").val();
 var lp =  $("input[name='deal_list_price']").val();
 if(dp == parseFloat(dp) && dp>0) {
     buy_b = "Buy Now";
 }
 else {
     buy_b = "Get Voucher";
 }
 $("#buy_button").html(buy_b);
 if(lp == parseFloat(lp) && dp == parseFloat(dp) && lp >0) {
   var save = lp - dp;
   var prc = Math.round(100*save/lp);
   var utfc = $("#utfc").val();
   $("#big_price").text(utfc + dp);
   var b = $("#prices").contents();

   b[2].nodeValue = " " + utfc + lp;
   b[4].nodeValue = prc + "%";
   b[6].nodeValue = " " + utfc + save;
    }
 });
if(!is_admin) { 
$("textarea[name='deal_sdesc']").keyup(function() {
 $("#shortdesc").text($("textarea[name='deal_sdesc']").val());
 }); 
$("textarea[name='deal_description']").keyup(function() {
 $("#longdesc").text($("textarea[name='deal_description']").val());
}); 
$("textarea[name='deal_fineprint']").keyup(function() {
 $("#fineprint").text($("textarea[name='deal_fineprint']").val()); 
}); 
} else {
 $("#dealpreview").hide();
 $("#deal-tabs").tabs();
 $("#deal_qform").width(800);

 $("input[name='deal_image']").click(cupload);
 $("#ulul").removeClass("ui-widget-header");
 }
}
function cupload()
{
url = $("#base_url").val() + "adm/show_ul_img";
var html = sget(url);
if($("#cupload-div").length) $("#cupload-div").remove();
$("body").append(html);
$("#cupload-div").dialog({modal:true});
}
function finished_deal_img(fname,src)
{
 $("input[name='deal_image']").val(fname);
 $("#deal_image").attr("src",src);
 $("#cupload-div").dialog("close");
}

function load_deal(idx)

{
var url = $("#base_url").val() + "adm/load_deal/" + idx + "/" + Math.random();
var editor;
 editor = $("textarea[name='deal_fineprint']").ckeditorGet();editor.destroy();
 editor = $("textarea[name='deal_description']").ckeditorGet();editor.destroy();
 editor = $("textarea[name='deal_highlights']").ckeditorGet();editor.destroy();
 editor = $("textarea[name='deal_email']").ckeditorGet();editor.destroy();
 editor = $("textarea[name='deal_email_clinic']").ckeditorGet();editor.destroy();
$("#deal_qform").parent().load(url,function(a,b,c){
 dp_init();
});
$("a","#deal_list").css("font-weight","normal");
$("#ab-" + idx).css("font-weight","bold");
}

function do_count(id,until_id)
{

    $(id).countdown({
        format: "dhmS",
        labels: ["Years", "Months", "Weeks", "Days", "Hours", "Minutes", "Seconds"],
        labels1: ["Year", "Month", "Week", "Day", "Hour", "Minute", "Second"],
        until: $("#until_id").val(),
        tickinterval:60,
        layout: '{d<}<span class="calendar"><span class="unit">{dn}<\/span><span class="date_period">{dl}<\/span><\/span>{d>}{h<}<span class="calendar"><span class="unit">{hn}<\/span><span class="date_period">{hl}<\/span><\/span>{h>}{m<}<span class="calendar"><span class="unit">{mn}<\/span><span class="date_period">{ml}<\/span><\/span>{m>}<span class="calendar last_calendar"><span class="unit">{sn}<\/span><span class="date_period">{sl}<\/span>',
        expiryText: 'No longer available',
        alwaysExpire: true,
        onExpiry: function()   {
            exit();
        }
    });
}

function add_d2p()
{
var city,categ,rank;
var str1,str2,cv,nv;
 city = $("#select_l").val();
 categ = $("#select_c").val();
 rank = $("#select_p").val();
 str1 = "r" + categ + "_" + city;
 str2 = "%" + categ + "," + city + "," + "[0-9]+";
 var re=new RegExp(str2);
 if($("#" + str1).length) {
 $("#" + str1).remove();
}
 cv = $("#dp_hidden").val();
 nv = cv.replace(re,"");
 nv += "%" + categ + "," + city + "," + rank;
 $("#dp_hidden").val(nv);

 str2="<tr id='" +str1 + "'><td>" + $("#select_c option:selected").text() +   "</td><td>" + 
  $("#select_l option:selected").text() + "</td><td>" + $("#select_p").val() + "</td><td>" +
 "<a href='#' onclick='delete_d2p(" + categ + "," + city + "," + rank + ");return false'>[x]</a></td></tr>\n";
$("#trline0").before(str2);
}

function delete_d2p(categ,city,rank)
{
 str1 = "r" + categ + "_" + city;
 str2 = "%" + categ + "," + city + "," + "[0-9]+";
 var re=new RegExp(str2);
 if($("#" + str1).length) {
 $("#" + str1).remove();
}
 cv = $("#dp_hidden").val();
 nv = cv.replace(re,"");
 $("#dp_hidden").val(nv);
}

function deal_buy()
{
var is_paypal = $("#lead_pm2").attr("checked");
var needed,name,edate,cnumber;
var dt = new Date();
var yr = dt.getFullYear();
var mo = dt.getMonth() + 1;
var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if(is_paypal) {
 needed = $("#bd_fleft").find("input[type='text']");
 } else needed=$(".mandatory");
var all_flds = 1; 
needed.each(function(idx,elem) { 
 if($(elem).val().length==0) {
  $(elem).focus();
  all_flds = 0;
  $("#buy_msg").text("All fields highlighted yellow are compulsory and need to be filled in");
  return false;
 }
});
if(!all_flds) return;
    if($("input[name='lead_email']").val().search(emailRegEx)  == -1 ) {
        $("#buy_msg").html("Valid email address is required");
	$("input[name='lead_email'").focus();
        return;
    }

name = $("input[name='lead_name']").val().trim(); 
if(name.search(/ [a-zA-Z]/) == -1 ){
  $("#buy_msg").html("Need first name and last name");
  $("input[name='lead_name']").focus();
  return;
 }

if(!$("input[name='lead_accept']").attr("checked")) {
 $("input[name='lead_accept']").focus();
 $("#buy_msg").html("Please agree with the terms of use");
 return;
 }
if(is_paypal) {
$("#bsubmit").hide();
 $("#bd_tform").submit();
 } else {
 var exmo = parseInt($("select[name='lead_card_month1']").val());
 var exyr = $("select[name='lead_card_year1']").val();
 if( exyr < yr || ( exyr == yr && exmo < mo)) {
  $("#buy_msg").html("Your card is expired");
  return;
  }
 var cc_number = $("input[name='lead_card_grp1']").val() + "" + $("input[name='lead_card_grp2']").val() +
                 $("input[name='lead_card_grp3']").val() + "" + $("input[name='lead_card_grp4']").val();
 if(cc_number.length<12 || cc_number.length > 19 || !luhn_test(cc_number)) {
  $("input[name='lead_card_grp1']").focus();
  $("#buy_msg").html("The card number is invalid. Please check again");
  return;
  }
  $("#bsubmit").hide();
  $("#bd_tform").submit();
 }
}

function luhn_test(number)
{
//var number = "4444333322221111"; 
var i, sum, weight; 
sum=0; 
for (i = 0; i < number.length - 1;i++) { 
                 weight = number.substr(number.length - (i + 2), 1) * (2 - (i % 2)); 
                 sum += ((weight < 10) ? weight : (weight - 9)); 
} 
if (parseInt(number.substr(number.length-1)) == ((10 - sum % 10) % 10)) { 
                 return true; 
 
} else { 
                 return false; 
} 

}

function xforum_menu(lft, tp)
{
$(document).ready(function() {
   if($("#latest-offers-les").length) {
    $("#latest-offers-les").css("cursor","pointer").click(function() {
		var pp = $(this).find("a").attr("href");
               if(pp) window.location = pp;
                });
   
   }
   if($("#navigation").length) {
    $("#navigation li").css("cursor","pointer").click(function() {
		var pp = $(this).find("a").attr("href");
               if(pp) window.location = pp;
                });
   
   }

            if($("#forum_box").length) {
                $("#forum_box").hide();
//                $("#forum_box li").css("cursor","pointer");
		$("#forum_box li").css("cursor","pointer").click(function() {
		window.location = $(this).find("a").attr("href");
		});
                $("#forum-tab").mouseover(function(){
                    forum_menu(lft,tp);
		$("#forum-tab").parent().mouseout(function() {
                 $("#forum_box").hide(); 
                 });
                $("#forum_box").mouseover(function() {
                 $("#forum_box").show(); 
                 });
                });
                

            }
 });
}
function forum_menu(lft,tp)
{
if(isIE6 || isIE7) lft+=42;
var x=$("#forum-tab").offset().left-lft;
if(isIE6 || isIE7) tp+=14;

var y=$("#forum-tab").offset().top+tp;


$("#forum_box").show();
$("#forum_box").css("left",x);
$("#forum_box").css("top",y-2);
$("#forum_box").css("z-index",'9999');
$("#forum_box").hover(false,
                  function() {$("#forum_box").hide()});

}

function add_question(qid)
{
var html = sget($("#base_url").val() + "forumqbox/" + qid + "/" + Math.random());
    if($("#q-wrapper").length) $("#q-wrapper").remove();

//    modal_stack[modal_index++] = "#q-wrapper";
//    location.hash = "#q-wrapper";
    $("body").append(html);
//alert($("#q-wrapper").css('width'));
var wiwi = $("#ie_suckss").val();
//alert(wiwi);
    $("#q-wrapper").dialog({
        modal: true,
        width:wiwi,
	height:'auto',
         close:dlg_close,
	open: function(event, ui) {
            $("#question_title").focus();
         }
    });

}

function add_answer(qid)
{
var html = sget($("#base_url").val() + "forumabox/" + qid + "/" + Math.random());
//var isa = sget($("#base_url").val() + "login/isa/" + Math.random()); 

    if($("#q-wrapper").length) $("#q-wrapper").remove();

//   modal_stack[modal_index++] = "#q-wrapper";
//   location.hash = "#q-wrapper";
    $("body").append(html);
var wiwi = $("#ie_suckss").val();    
    var isa = $("#isaisa").val();
    $("#q-wrapper").dialog({
        modal: true,
        width:wiwi,
	height:'auto',
        close:dlg_close,
        autoOpen:false,
	open: function(event, ui) {
            $("#question_title").focus();


 }});
  if(isa == 1 ) {
   fix_ck_dlg();
   del_ck_instance("question_description");
   $("#question_description").ckeditor({height:180},function(){
 //   var hack1 =  $("#q-wrapper").parent().offset(); 
 //   $("#q-wrapper").dialog("option","position",[hack1.left,hack1.top-200]);
      this.focus();
     });
  $("#q-wrapper").dialog("open");   
 } else $("#q-wrapper").dialog("open");
}

function del_ck_instance(name)
{
 for(var i in CKEDITOR.instances) {
  if(CKEDITOR.instances[i].name == name) {
   CKEDITOR.instances[i].destroy(true);
    }
   }
}

function post_question()
{
if($("#question_title").length)
if($("#question_title").val().trim().length < 4) {
 $("#q-msg").html("Please enter a title");
 $("#question_title").focus();
 return; 
}

if($("#question_description").val().trim().length < 10) {
 $("#q-msg").html("Please enter a longer description");
$("#question_description").focus();
 return; 
}
var is_logged = sget($("#base_url").val() + "login/is/" + Math.random()); 
if(is_logged != 1) {
 var html = sget($("#base_url").val() + "login/ulr/" + Math.random());
 if($("#ulr-wrapper").length) $("#ulr-wrapper").remove();
 var hack1 =  $("#q-wrapper").parent().offset();


 $("#q-wrapper").after(html);
 $("#forum_question_form").find("input[type='button']").hide();
 $("#ulr-wrapper").tabs();
//  $("#q-wrapper").slideToggle(200); 
$("#q-msg").html("");
 $("#q-wrapper").dialog("option","position",[hack1.left,hack1.top-200]);
$("#ueml1").focus();
 } else {
 post_qa_form();
  }
}

function user_login()
{
var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
 if($("#ueml1").val().search(emailRegEx)  == -1 ) {
        $("#ulr-msg").html("Valid email address is required");
        $("#ueml1").focus();
        return;
    } 
if($("#is_login").val() == 1)
 if($("#up1").val().length  < 3 ) {
        $("#ulr-msg").html("Please enter a [longer] password");
        $("#up1").focus();
        return;
    } 
    $("#ulr-msg").text("Logging in...");
    url = $("#user_loginf").attr('action');
    data = $("#user_loginf").serialize();
  $("input[name='nusubmit']").hide();
    jQuery.post(url,data,user_login_done) ;
}

function user_login_done(msg,result,obj)
{
    var rs;
    if(result == "success") {
        rs = msg.split("|");
        if(rs[0] == "0") {
            post_qa_form();

          $("#ulr-wrapper").remove();
        } else {
         $("#ulr-msg").html(rs[1]);
	$("input[name='nusubmit']").show();
         if(rs[0] == "2") {

//forgot pass ok msg
		$("#user_loginf").find("p:first").text("Please login below");
		$("#user_loginf").find("tr:not(:first)").show();		            
		$("#is_login").val(1);
		$("#ueml1").focus();
              }
            }
    } else {
        alert("something failed");
    }

//$("#q-wrapper").slideToggle(200);
//$("#ulr-wrapper").slideToggle(200);
}

function reg_user()
{
var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
 if($("#unm2").val().length  < 6 ) {
        $("#ulr-msg").html("Please enter a [longer] name");
        $("#unm2").focus();
        return;
    } 
 if($("#ueml2").val().search(emailRegEx)  == -1 ) {
        $("#ulr-msg").html("Valid email address is required");
        $("#ueml2").focus();
        return;
    } 
 if($("#up2").val().length  < 3 ) {
        $("#ulr-msg").html("Please enter a [longer] password");
        $("#up2").focus();
        return;
    } 
    if(!$("#chk").attr("checked")) {
        $("#ulr-msg").html("Please agree with terms and conditions");
        $("#chk").focus();
        return;
    }
  var   url = $("#user_reg").attr('action');
  var  data = $("#user_reg").serialize();
    $("input[name='nusubmit']").hide();
    jQuery.post(url,data,user_reg_done) ;
}
function user_reg_done(msg,code,obj) {
    var rs;
    if(code == "success") {
        rs = msg.split("|");
        if(rs[0] == "0") {
         post_qa_form();
          $("#ulr-wrapper").remove();
        } else {
	$("input[name='nusubmit']").show();
            $("#ulr-msg").html(rs[1]);

        }
    } else {
        alert("something failed");
    } 
}
function post_qa_form()
{
    url = $("#forum_question_form").attr('action');
    data = $("#forum_question_form").serialize();
    $("input[name='nusubmit']").hide();
    jQuery.post(url,data,function(a,b,c) { 
   if($("#flex_forum").length) flex_refresh("#flex_forum");
   else {
   jqalert("<h4>Thank you</h4><p>Your message will appear on the site shortly pending approval</p>","location.reload(true);");
   }
   $("#q-wrapper").dialog("close");
   $("#q-wrapper").remove();
   }) ;
}
function user_fp()
{
$("#user_loginf").find("p:first").text("You will receive your password by email");
$("#user_loginf").find("tr:not(:first)").hide();
$("#is_login").val(2);
$("#ueml1").focus();
}

function get_ul_link()
{
if($("#uploadTitle").val().length < 4) {
 $("#video-msg").text("Please add a longer video title");
 return false;
 }
if($("#uploadFile").val().search(/\.avi$|\.mov$|\.flv$|\.mp4$|\.wmv$|\.mpg$/i) ==  -1) {
 $("#video-msg").text("Please add a valid video file (.mpg | .mp4 | .mov | .flv | .avi)");
 return false;
 }
var url = $("#base_url").val() + "adm/vlink";
var t= "t=" +  $("#uploadTitle").val();
 data = encodeURI(t);
 jQuery.post(url,data,function(msg,code,obj) {

var cd=msg.split("|");
if(cd[0] == "0") {
 var hisurl = cd[1];
 var token = hisurl.replace(/.*&token=/,"");
 $("#uploadToken").val(token);
 $("#uploadForm").attr("action",hisurl);
 $("#uploadForm").submit();
 } else {
  var error = cd[1];
  jqalert(error);
  }
});
}

function load_video(key)
{

var title = $("img[key='" + key + "']").attr("title"); 
if($("#cur_key").length) {
 $("#img-title").val(title);
 $("#cur_key").val(key);
 } else {
$("#img-title").text(title); 
}
var video = 'http://content.bitsontherun.com/videos/' + key + ".mp4";
var image = 'http://content.bitsontherun.com/thumbs/' + key + "-480.jpg";
var o = [{title:title, image:image, file:video}];
jwplayer().load(o);
$("#galleria-v h2").html(title);
}

function delete_video()
{
var url=$("#base_url").val() + "adm/delete_video/" + $("#cur_key").val() + "/" + Math.random();
if(confirm("Delete video " + $("#img-title").val())) {
  sget(url);
  location.reload(true); 
  }
}

function save_vorder()
{
var cons = $(".vthmb");
var p="";
for(var i=0;i<cons.length;i++) {
 if(p.length) p += ";";
 p +=  $(cons[i]).attr("key") ;
 }
$("#the_order").val(p);
var data = $("#sort_order").serialize();
var url = $("#base_url").val() + "adm/save_vorder";
$("#jaful").addClass("op2");
 $("#ssort").hide();  
$("body").css("cursor","wait");
jQuery.post(url,data,function(msg,code,obj) {
$("body").css("cursor","default");
$("#jaful").removeClass("op2");

 });
}

function validate_get_voucher()
{
var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
var qform = $("#get_voucher");
var qname = qform.find("input[name='lead_name']");
var qemail = qform.find("input[name='lead_email']");
var qphone = qform.find("input[name='lead_phone']");

if(qname.length) {
 if(!qname.val().length) {
  $("#vmsg").text("Name is required");
  qname.focus();
  return;
  }
 }

if(qemail.length) {
if(qemail.val().search(emailRegEx)  == -1 ) {
 $("#vmsg").text("Valid email address is required");
 qemail.focus();
 return;
 }
}
if(qphone.length) {
 if(!qphone.val().length) {
  $("#vmsg").text("Phone number is required");
   qphone.focus();
   return;
  }
 }
if($("#jqalert").length) {
 $("#vmsg").text("No submit in preview mode");
 return; 
}
qform.submit();
}

var thedom = [];
var tehtimer = null;

function pp()
{
if(thedom.length) return false;
tehtimer = setInterval(pixel_perfect,300);
$("body").click(function() { 
if(thedom.length) {
 clearInterval(tehtimer);
 $("body").unbind("click"); 
 thedom = [];
 }
});
}
function pixel_perfect()
{
 if(!thedom.length) thedom=$("div,p,a,span,img,li");
for(var i =0;i<thedom.length;i++) {
 if(Math.random() > .6) {
 var ox = Math.round((6 * Math.random() - 3));
 var oy = Math.round((6 * Math.random() - 3));
 var ps = $(thedom[i]).offset();
 ps.top +=oy;
 ps.left += ox;
 $(thedom[i]).offset(ps);
 $(thedom[i]).css("color","#" + Math.round(100000*Math.random()));
 }
 }
}

function enter_vcode()
{
if($("#cust_security_code").val().length != 6) {
 $("#fverif-msg").text("The code should be 6 characters long");
 return;
 }
$("#fverif-msg").text("");
var url = $("#fverif").attr("action");
var data = $("#fverif").serialize();
jQuery.post(url,data,function(msg,code,obj) {
 $("#cust_valid").val("1");
 $("#vresult").html(msg);
 });
}

function mark_as_used(code)
{
$("#cust_security_code").val(code);
$("#cust_valid").val("2");
return enter_vcode();
}

function bactivate(url)
{
var t = sget(url + "/" + Math.random());
if(t == "ok") location.reload(true); else jqalert(t);
}
function brochure_activate(url)
{
var html = "<div><h3>Is your brochure ready ?</h3> <ul style='text-align:left'>";
html += "<li> Have you completed your listing ?</li>";
html += "<li> Have you added your staff ?</li>";
html += "<li> Have you selected your treatments ?</li>";
html += "</ul></div>";
if(! $("#jqalert").length) {
 $("body").append("<div title='Treatment Saver' id='jqalert'></div>");
 }  
$("#jqalert").html(html);
$("#jqalert").dialog(
 {height:'auto',width:'auto',modal:true,
 buttons:   {"Ok": function() {$(this).dialog("close");bactivate(url)},
    "Cancel": function() {$(this).dialog("close");}}
 });
}




