var locker=null,
    gmap2=null,
    geocoder=null,
    radius_type=null,
    radius=null;

try{
  tinyMCE.init({
    mode : "textareas",
    theme : "simple"
  });
}catch(e){}

function display_map(map){
  $(map).setStyle({zIndex: 1000, visibility: 'visible'});
}

function hide_map(id){
  $(id).setStyle({zIndex: -100, visibility: 'hidden'});
}

function showMapItFlash(link,id){
  var domLink=$(link);
  var domPopup=$(id);
  document.body.appendChild(domPopup);

  var linkOffset=domLink.cumulativeOffset();
  domPopup.style.left=(linkOffset[0]-190)+'px';
  domPopup.style.top=linkOffset[1]+'px';
}

function closeMapItFlash(x){
  $(x?$(x):select_ok.close_id).style.top='-10000px';
}

function unlock_error(err){
  locker.unlock();
  alert(err);
  return false;
}

function finish_map_selection(response){
  if(response.status!=200)
    return unlock_error("Request error: "+response.status+" "+response.statusText);

  if(!(resp=response.responseJSON))
    return unlock_error("Server error!");

  if(resp.bad_selection)
    return unlock_error("Bad selection!");


  if((state=$('user_state_id')))
    state.value=resp.state_id?resp.state_id:'';

  if((country=$('user_country_id'))){
    country.value=resp.country_id;
    show_hide_us(country,$('user_state_id').up('tr'));
  }


  $('user_hometown').value=resp.city?resp.city:'';
  $('user_lat').value=resp.lat;
  $('user_lon').value=resp.lon;

  locker.unlock();
  closeMapItFlash();
}

function select_ok(val,id){
  select_ok.close_id=id;

  if(!val)
    return closeMapItFlash();

  if(!(res=gmap.position()))
    return alert("Please select your location.");


  if(!locker)
    locker=new Locker($('map_holder'));

  locker.lock();

  new Ajax.Request('/users/resolve_codes',{method: 'POST',parameters: res,onComplete: finish_map_selection});
}

var RadiusTable=Class.create({});

RadiusTable.forge_keys=$A([Event.KEY_BACKSPACE,
                 Event.KEY_TAB,
                 Event.KEY_RETURN,
                 Event.KEY_ESC,
                 Event.KEY_LEFT,
                 Event.KEY_UP,
                 Event.KEY_RIGHT,
                 Event.KEY_DOWN,
                 Event.KEY_DELETE,
                 Event.KEY_HOME,
                 Event.KEY_END,
                 Event.KEY_PAGEUP,
                 Event.KEY_PAGEDOWN]);

Object.extend(RadiusTable.prototype,{
  initialize: function(obj){
    Object.extend(this,obj);
    this.markers={};

    this.base_element=$(this.base_element);
    this.table=$(this.table);

    if((this.map_holder||(this.map_options&&this.map_options.element))&&!this.delayed_create)
      this.create_map();
  },

  insert_row: function(){
    this.table.insert({bottom: this.partial});
    return this.get_elements(this.table.rows[this.table.rows.length-1]);
  },

  get_elements: function(row){
    var t,ret={};
    row=$(row);

    if(row.hasClassName('notification-area-errors'))
      return null;

    ret.row=row;
    ret.go_to=row.down('a.goto-area');
    ret.remove=row.down('a.remove-area');

    if((t=row.previous('tr'))&&t.hasClassName('notification-area-errors'))
      ret.errors_row=t;

    var name,re=/\[([^\]]+)\]$/;
    var inputs=row.select('input');

    for(var i=0;i<inputs.length;++i){
      if((name=inputs[i].name.match(re))&&name[1])
        ret[name[1]]=inputs[i];
    }

    return ret;
  },

  set_up_row: function(circle,row,data){
    var self=this;
    row.go_to.observe('click',function(){self.go_to(circle);});
    row.remove.observe('click',function(){self.remove(circle);})

    this.mask_input(row.radius_km,"0123456789",".",function(x,y){self.set_radius_km(circle,x,y);});
    this.mask_input(row.lon_center,"0123456789",".-",function(x,y){self.set_lat_lon(0,circle,x,y);});
    this.mask_input(row.lat_center,"0123456789",".-",function(x,y){self.set_lat_lon(1,circle,x,y);});

    this.set_row_data(row,data);
  },

  set_row_data: function(row,data){
    for(var i in data){
      if(i in row&&Object.isElement(row[i]))
        row[i].value=data[i];
    }  
  },
  
  mask_input: function(elem,repeatable,once,trigger){
    var prev_val=null,should_trigger=false;
    elem=$(elem);

    elem.observe('keyup',function(){
      if(should_trigger&&prev_val!=this.value&&trigger)
        trigger(prev_val=this.value,this);
    });

    elem.observe('keypress',function(evt){
      evt=evt?evt:window.event;
      var keyCode=evt.which?evt.which:evt.keyCode;

      if(RadiusTable.forge_keys.indexOf(keyCode)!=-1||evt.ctrlKey||evt.altKey){
        should_trigger=true;
        return;
      }

      var c=String.fromCharCode(keyCode);
      if(repeatable.indexOf(c)==-1&&(once.indexOf(c)==-1||this.value.indexOf(c)!=-1)){
        Event.stop(evt);
        should_trigger=false;
      }else should_trigger=true;
    });
  },

  remove: function(circle){
    this.map.remove_circle(circle);
  },

  set_radius_km: function(circle,value){
    value=parseFloat(value);
    if(isNaN(value)||value==0.0){
      circle.set_radius_null();
      return;
    }
    circle.set_radius_km(value);
  },

  get_cursor_pos: function(e){
    if(e.createTextRange){
      var r=document.selection.createRange().duplicate();
      r.moveEnd('character',e.value.length);
      return (r.text==''?e.value.length:e.value.lastIndexOf(r.text));
    }
    return e.selectionStart;
  },

  valid: function(){
    for(var i in this.markers){
      if(this.markers[i].lat_center.hasClassName('error-radius-input')||
          this.markers[i].lon_center.hasClassName('error-radius-input')||
          this.markers[i].radius_km.hasClassName('error-radius-input'))
        return false;
    }
    return true;
  },

  force_serialization: function(){
    for(var i in this.markers)
      this.set_row_data(this.markers[i],this.markers[i].circle.get_bbox());
  },

  set_cursor_pos: function(i,pos){
    i.focus();
    if(i.createTextRange){
      var range=i.createTextRange();
      range.collapse(true);
      range.moveEnd('character',pos);
      range.moveStart('character',pos);
      range.select();
    }else if(i.setSelectionRange){
      i.setSelectionRange(pos,pos);
    }
  },

  set_lat_lon: function(lat,circle,value,e){
    e=$(e);
    value=parseFloat(value);
    if(isNaN(value)||(lat ? (value<-90||value>90) : (value<-180||value>180))){
      e.addClassName('error-radius-input');
      return;
    }
    e.removeClassName('error-radius-input');

    //var t=this.get_cursor_pos(e);//wont work :(
    circle[lat ? 'set_lat' : 'set_lon'](value);
    //this.set_row_data(this.markers[circle],circle.get_bbox());
    //this.set_cursor_pos(e,t);
  },

  unique_id: function(){
    var str;

    do{
      str=Math.random().toString().substring(2);
    }while(str in this.markers);

    return str;
  },

  go_to: function(circle){
    if(circle.id in this.markers){
      this.map.setCenter(circle.opts.position,circle.opts.zoom);
      this.map.redrag_all();
    }
  },

  on_create: function(circle,position){
    circle.id=this.unique_id();
    this.markers[circle.id]=circle.opts.row ? circle.opts.row : this.insert_row();
    this.markers[circle.id].data=circle.opts.bbox ? circle.opts.bbox : circle.get_bbox();
    this.markers[circle.id].circle=circle;
    this.set_up_row(circle,this.markers[circle.id],this.markers[circle.id].data);
  },

  on_move: function(circle,position,finished){
    if(finished||!(circle.id in this.markers))
      return;

    this.markers[circle.id].lat_center.value=position.lat();
    this.markers[circle.id].lon_center.value=position.lng();
  },

  on_radius: function(circle,finished){
    if(finished||!(circle.id in this.markers))
      return;

    this.markers[circle.id].radius_km.value=circle.radius_km(true);
  },

  on_change: function(circle){
    if(!(circle.id in this.markers))
      return;

    this.set_row_data(this.markers[circle.id],circle.get_bbox());
  },

  on_remove: function(circle){
    if(circle.id in this.markers){
      this.table.deleteRow(this.markers[circle.id].row.rowIndex);
      if(this.markers[circle.id].errors_row)
        this.table.deleteRow(this.markers[circle.id].errors_row.rowIndex);

      delete this.markers[circle.id];
    }
  },

  build_params: function(cont,row){
    var x=false,t=parseFloat(row.radius_km);
    if(isNaN(t)||t==0.0){
      t=0;
      x=true;
    }

    return {
      radius_km: t,
      row: cont,
      bbox: row,
      radius_is_null: x,
      lat: parseFloat(row.lat_center),
      lon: parseFloat(row.lon_center),
      zoom: (row.zoom.length>0 ? parseInt(row.zoom) : null)
    };
  },

  field_values: function(row){
    var ret={};
    for(var i in row){
      if(Object.isElement(row[i])&&!Object.isUndefined(row[i].value))
        ret[i]=row[i].value;
    }
    return ret;
  },

  map_created: function(){
   return !Object.isUndefined(this.map);
  },

  create_map: function(){
    var opts=this.map_options ? Object.clone(this.map_options) : {};

    if(Object.isUndefined(opts.element))
      opts.element=this.map_holder;

    opts.on_create=this.on_create.bind(this);
    opts.on_remove=this.on_remove.bind(this);
    opts.on_move=this.on_move.bind(this);
    opts.on_radius=this.on_radius.bind(this);
    opts.on_change=this.on_change.bind(this);

    if(this.table.rows.length>1){
      opts.markers=[];
      for(var i=1;i<this.table.rows.length;++i){
        var row=$(this.table.rows[i]);
        if(row.hasClassName('notification-area-errors'))
          continue;

        var t=this.get_elements(row);
        opts.markers.push(this.build_params(t,this.field_values(t)));
      }
    }
    
    this.map=new UBAGoogleMapsCircled(opts);
  }
});

function radius_change(obj){
  radius.value=obj.radius_km(true)/parseFloat(radius_type.value);
}

function measure_change(){
	radius =  $('user_notification_radius');
	if(!radius.value.match(/^\s*$/))
    radius.value=(miles()? parseFloat(radius.value)/1.609344 : parseFloat(radius.value)*1.609344);
}

function gmap_search(value){
  if(value.match(/^\s*$/)){
    alert('Please enter the value.');
    return;
  }

  gmap2.do_search(value);
}

function check_notification_area(form,evt){
  var t;
  if((t=$('i_agree'))&&!t.checked)
    return;

  if((t=$('user_recive_messages'))&&t.nodeName=='INPUT'&&t.type.toLowerCase()=='checkbox'&&!t.checked)
    return;

  if($('user_whole_world_0').checked&&$('user_notification_lat_cr').value.blank()){
    alert('Please select the area.');
    Event.stop(evt);
    return false;
  }
  
  if(miles()){
    $('radius_type').value='km';
    measure_change.apply($('radius_type'));
  }
  
}

function set_up_hidden(form,evt){
  var c1=$('user_notify_by_email');
  var c2=$('user_notify_by_sms');
  $('user_notification_type').value=((c1.checked?parseInt(c1.value):0)|(c2.checked?parseInt(c2.value):0));
}

function miles(){
  return $('radius_type').value=='miles';
}

function normalize_lat(v){
  var v=parseFloat(v);

  if(v>90)
    v=90;
  else if(v<-90)
    v=-90;

  return v.toString();
}

function normalize_lon(v){
  var v=parseFloat(v);

  if(v>180)
    v=180;
  else if(v<-180)
    v=-180; 

  return v.toString();
}

function getDataFromFlash(str){
  var t=str.split(',');
  try{
    var lon=parseFloat(t[0]);
    var lat=parseFloat(t[1]);
    var radius=parseFloat(t[2]);

    $('user_notification_lat_cr').value=lat;
    $('user_notification_lon_cr').value=lon;
    $('user_notification_lat_tl').value=normalize_lat(lat+radius);
    $('user_notification_lon_tl').value=normalize_lon(lon-radius);
    $('user_notification_lat_br').value=normalize_lat(lat-radius);
    $('user_notification_lon_br').value=normalize_lon(lon+radius);
    $('user_notification_radius').value=degree_to_km(radius)/(miles()?1.609344:1);
  }catch(e){}
}

  function profileSubmit(event) {
	  set_up_hidden();

    $('my_ubalert_form').request({
        onFailure: function() { },
        onSuccess: function(t) {
            response = t.responseText.evalJSON();
			if(response.success) {
				$('error_wrapper').update('');
				if (response.data.img_url) {
					$('top_user_avatar').setAttribute('src','/resampled/100x100-crop/uploads/'+response.data.img_url);
				}
				new PopupDiv("<h3>Notice<\/h3><br/>Your information was updated", '500px');
			} else {
				$('error_wrapper').update(response.data);
			}
        }
    });
    Event.stop(event);
}


var SMSVerification=Class.create({
	initialize: function() {
		this.getPinWin = false;
		this.verifyWin = false;
	},
	showPinWin: function() {
    	var phone = $F('user_sms_num');
    	var code = $F('sms_country_code');
		if (phone && code) {
			this.phone = phone;
			this.code = phone;
			new Ajax.Request('/phone_verification', {
				method: "POST",
				parameters:{
					'get_me_pin': true,
					'phone':phone,
					'code':code
				}, 
				onSuccess: this.showPinWinPopup.bind(this),
				onFailure: this.showPinWinPopup.bind(this)
			});
		} else {
			this.showNotice("We could not verify your phone.  Please check the number and try again.");
		}
  	},
  	showPinWinPopup: function(data) {
  		if (data.responseJSON) {  			
  			if (data.responseJSON.success) {
				this.getPinWin = new PopupDiv(data.responseJSON.data, '400px');
			} else {
				this.getPinWin = new PopupDiv("<h3>Error<\/h3><br/>"+data.responseJSON.data+"", '400px');
			}
		}
	},
  	showverifyWinPopup: function(data) {  		
  		if (data.responseJSON) {
  			if (data.responseJSON.success) {
  				this.closePinWin();
				//this.showNotice("Thank you. Your phone has been verified.");
				$('sms_verification_block').update('<p style="color:green"><img src="./img/icons/action_apply.png">Phone number is verified</p>');
			} 
			this.showNotice(data.responseJSON.data);
		}
	},
  	closePinWin: function() {
  		this.getPinWin.close();
  		this.getPinWin = false;
	},
  	closeverifyWin: function() {
  		this.verifyWin.close();
  		this.verifyWin = false;
	},
  	showverifyWin: function() {
			var pin = $F('verification_pin');
			if (pin) {		
					new Ajax.Request('/phone_verification', {
						method: "POST",
						parameters:{
							'verify': true,
							'pin':pin
						}, 
						onSuccess: this.showverifyWinPopup.bind(this)
					});
			} else {
				this.showNotice("Please enter a PIN");
			}
  	},
  	showNotice: function(content) {
		new PopupDiv("<h3>Notice<\/h3><br/>"+content+"", '400px');
	}
	
});
  
function smsCodeChange(val) {
	$('phone_code_display').update('+'+val+' ');
}
  
var SMSV = new SMSVerification();