﻿// JScript File
if( typeof($) == 'undefined' ){
  $=function(id){return document.getElementById(id);}
}
///The initialization data structure for the Address control
/// cfg{
/// baseName:''
/// }
/// 
var Address = function(cfg)
{
    this.cfg = cfg;
    this.baseName = cfg.src;
    this.parentDiv = null;/*This is the parent div */
    this.PersistNotify=null;
    this.initialized = false;
}
Address.prototype.Show=function()
{

//    this.parentDiv.style.display='';
    this.Clear(); this.LoadCtx();
    this.dlg.show();
}
Address.prototype.Hide = function()
{
    this.parentDiv.style.display='none';
}
Address.prototype.Check = function()
{
    var ok=true;
    if( this.addr1 && this.addr2 && this.state && 
        this.city && this.zip && this.ctx &&
        this.error && this.cancel && this.save )
    { return ( this.initialized = true ); }
    return false;
}
Address.prototype.LoadCtx=function(){
    var c=this.ctx.value;
    var vals = this.toJson(c);
    this.addr1.value=vals.addr.addr1;
    this.addr2.value=vals.addr.addr2;
    this.city.value=vals.addr.city;
    DOM.selectDdlText(this.state,vals.addr.state);
    this.zip.value=vals.addr.zip;
}
Address.prototype.toJson = function(val){
    var v = val.split('');
    if( v[0]=='{' ) return val;
    v = val.split("|");
    var res = {addr:{addr1:'',addr2:'',addr3:'',city:'',state:'',county:'',country:'',zip:'',zipp:''}};
    var le = v.length,nv=[],ke='',va='';
    for( var i=0;i<le;i++){
        nv=v[i].split(":");
        ke=nv[0];va=(nv.length==2)?nv[1]:"";
        switch( nv[0] ){ 
            case 'addr1':res.addr.addr1=va;break;
            case 'addr2':res.addr.addr2=va;break;
            case 'state':res.addr.state=va;break;
            case 'city':res.addr.city=va;break;
            case 'zip':res.addr.zip=va;break;
        }
    }
    return res;
}
/*
needs the elements in the following layout. 
pdiv=<cfg.src>_divAddr, <cfg.src>_divAddrCtx, 
<cfg.pdiv>_elements,<cfg.pdiv>_imgSave, <cfg.pdiv>_imgCancel
*/
Address.prototype.Init = function()
{
    var pDiv = this.baseName+"_divAddr";
    this.parentDiv = $(pDiv);
    this.chk = $(this.baseName+"_lnkChangeAddress");
    this.ctx = $(this.baseName+"_divAddrCtx");
    if( typeof(this.cfg.pdiv)=="undefined") pDiv = this.baseName+"_mdAddress";
    else pDiv = this.cfg.pdiv;
    this.check = $(pDiv+"_chkShippingAddr");this.errdiv=$(pDiv+"_divError");
    this.addr1 = $(pDiv+"_txtAddr1"); this.addr1err = $(pDiv+"_iaddr1");
    this.addr2 = $(pDiv+"_txtAddr2");this.addr2err = $(pDiv+"_iaddr2");
    this.state = $(pDiv+"_ddlState");this.stateerr = $(pDiv+"_istate");
    this.city = $(pDiv+"_txtCity");this.cityerr = $(pDiv+"_icity");
    this.zip = $(pDiv+"_txtZip");this.ziperr = $(pDiv+"_izip");
    this.error = $(pDiv+"_lblError");
    this.cancel = $(pDiv+"_imgCancel");
    this.save = $(pDiv+"_imgSave");
    
    if( typeof(PopupDefaultConfig) == "undefined" ){
        this.dlg = { show:function(){}}
    }
    else{
        var cfg = new PopupDefaultConfig();
        cfg.element=$(this.baseName+"_mdAddress");
        cfg.enabledrag=cfg.footer=false;
        cfg.close={ imageurl:'i.ashx?i=common/window_close.gif', //close icon
            onunload: delegate(this,this.Clear) };
        cfg.styles.header="clsTitle";
        cfg.styles.content='clsContent';
        cfg.styles.container=cfg.styles.title='';
        cfg.size = {width:"401px"};
        cfg.position={left:'250px',top:'20px'};
        cfg.usedivlayout=cfg.showtitle=true;
        cfg.buttons = [];cfg.title=this.cfg.title;
        cfg.buttons.push( {type:"ok", id: this.save.id, handler: delegate(this,this.OnValidate) } );
        cfg.buttons.push( {type:"cancel", id: this.cancel.id, handler: delegate(this,this.OnCancel) } );
        this.dlg = new PopupDialogBox(cfg); 
        Sys.Application.add_init(delegate(this.dlg, this.dlg.initialize));
        //Sys.Application.add_init(delegate(this.dlg, this.dlg.show));
    }
    this.dlgSave = delegate(this,this.OnClick);
    this.addr="";
    if( this.Check() )
    { 
        if( !this.cfg.inline ) this.Hide(); 
        if(this.chk) $addHandler(this.chk,"click", delegate(this, this.Show));
        if(this.save) $addHandler(this.save,"click",this.dlgSave);
        if(typeof(this.cfg.validate) != "undefined") $addHandler(this.save,"click",delegate(this,this.OnValidate));
    }
    else this.ShowError('error mapping elements.');
}
Address.prototype.ShowError = function( msg ){
    if( this.error != null ) this.error.innerHTML = msg;
}
Address.prototype.ShowErr = function(arr){
    if( arr && arr.length > 0 ) this.errdiv.style.display='';
    for(var i in arr) if( arr[i] ) arr[i].style.display='';
}
Address.prototype.OnClick = function( src ){
}
Address.prototype.OnCancel = function( src ){
}
Address.prototype.OnValidate = function( src ){
    var res = this.validateData(src);
    return res;
}
Address.prototype.Validate = function(e){
    var valid = true;
    var msg = "";
    if( this.addr1.value.length == 0 ) { msg="Address line1 is invalid.&nbsp;"; valid = false; }
    if( this.city.value.length == 0 ) { msg+="City is empty.&nbsp;"; valid = false; }
    if( this.zip.value.length != 5 ) { msg+="Zip has invalid value.&nbsp;"; valid = false; }
    if( !valid ){ src.preventDefault(); src.stopPropagation(); if(event) event.returnValue = false; this.ShowError( msg ); }
    else { this.CheckAddress();this.persistChange(); }
    return msg;
}
Address.prototype.validateData = function()
{
    var valid = true;
    var msg = "", flds=[], errs=[];
    this.ClearErr();
    if( this.addr1.value.length == 0 ) { msg="Address line1 is required.<br />"; valid = false; flds.push(this.addr1err); }
    if( this.city.value.length == 0 ) { msg+="City is required.<br />"; valid = false;flds.push(this.cityerr); }
    if( this.state.selectedIndex == 0 ){msg+="State is required.<br />"; valid = false; flds.push(this.stateerr); }
    if( this.zip.value.length != 5 ) { msg+="Zip is required.<br />"; valid = false; flds.push(this.ziperr); }
    if( !valid ){ this.ShowError( msg ); this.ShowErr(flds); }
    else { this.CheckAddress();this.persistChange();  }
    return valid;
}
Address.prototype.persistChange = function()
{
    var c = "";
    c = "addr1:"+this.addr1.value+"|";
    c += "addr2:"+this.addr2.value+"|";
    c += "state:"+this.state.options[this.state.selectedIndex].text+"|";
    c += "city:"+this.city.value+"|";
    c += "zip:"+this.zip.value+"|";
    if( this.check ) c += "chk:"+this.check.checked+"|";
    this.ctx.value = c;
    this.addr = this.addr1.value+" "+this.addr2.value+"<br /> "+
    this.city.value+" "+this.state.options[this.state.selectedIndex].text+" "+this.zip.value;
    if( this.PersistNotify ) this.PersistNotify();
    this.Clear();
}
Address.prototype.IsEmpty = function()
{
    if( this.addr1.value.trim().length == 0 &&
        this.addr2.value.trim().length == 0 &&
        this.city.value.trim().length == 0 &&
        this.zip.value.trim().length == 0 )
    return false;
    else return true;
}
Address.prototype.Clear = function()
{
    this.addr1.value = this.addr2.value = this.city.value = this.zip.value = '';
    this.state.selectedIndex = 0;this.ClearErr();
}
Address.prototype.ClearErr=function(){
    this.addr1err.style.display = this.addr2err.style.display = this.cityerr.style.display = this.ziperr.style.display = 
    this.stateerr.style.display = this.errdiv.style.display = 'none';this.error.innerHTML='';
}
Address.prototype.CheckSuccess = function(o){
    //alert('success');
    if(o.responseText != undefined ){
    }
}
Address.prototype.CheckFailure = function(o){
    //alert('failure');
    if( o ){}
}
Address.prototype.CheckAddress = function(){
    var ele=this.ele;
    var postData =  "addr1="+this.addr1.value+"&addr2="+this.addr2.value+"&addr3="+
                    "&city="+this.city.value+"&state="+this.state.value+
                    "&zip="+this.zip.value+"&zipp="+"&frmt=json";
    var callback =
    {
      success:delegate(this,this.CheckSuccess),
      failure: delegate(this,this.CheckFailure)
    };
    
    var sUrl = "/webservice/addressvalidate.asmx/ValidateAddress?"+Math.floor(Math.random() * 1000000);    
    var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback, postData);
}
