/* For New Selection Form */

if ( !window.SMState ) window.SMState = {
  'SelectedIndustryIDs' : [],
  'SelectedCityIDs' : [],
  'SelectedTitleAIDs' : [],
  'SelectedTitleBIDs' : [],
  'SelectedJobTypeIDs' : [],
  'locations' : [],
  'industrytypes' : [],
  'jobtitles' : [],
  'listeners' : [],
  'addListener' : function(func){this.listeners.push(func)},
  'removeListener' : function(func){
      
    },
  'updateListeners' : function(event){
      var i = 0;
      var l = this.listeners.length;
      while( i < l ) {
        this.listeners[i].call(this, event);
        i++;
      }
    },
  'addIndustryID' : function(id){
    var id = parseInt(id);
    var l = this.SelectedIndustryIDs.length;

    if ( id == 1 || ( l == 1 && this.SelectedIndustryIDs[0] == 1 ) ) {
      this.SelectedIndustryIDs = [];
    }
    
    if ( id != 1 ) {
      $('#industry2').trigger('click').trigger('updateState');
    }
    
    if ( this.SelectedIndustryIDs.length < 10 ) {
      this.SelectedIndustryIDs.push( parseInt(id) ); 
      this.updateListeners( {'type':'industry','data':id} );
    }
   },
  'removeIndustryID' : function(id) {
     var id = parseInt(id);
     var arr = SMState.SelectedIndustryIDs;
     var idx = $.inArray(id, arr);
     if ( idx > -1 ) {
       arr.splice( idx, 1 );
       this.updateListeners( {'type':'industry','data':id} );
     }
   },
  'addTitleID' : function(tid, id) {
    var id = parseInt(id);
    if ( SMState.SelectedJobTypeIDs.length <= 2 ) {
      var idx = $.inArray( id, SMState.SelectedJobTypeIDs );
      if ( idx == 0 ) {
        SMState.SelectedTitleAIDs.push( parseInt(tid) );
      } 
      if ( idx == 1 ) {
        SMState.SelectedTitleBIDs.push( parseInt(tid) );
      }
    }
    this.updateListeners( {'type':'jobtype','data':id} );
   },
  'removeTitleID' : function(id) {   
     var id = parseInt(id);  
     var arr1 = SMState.SelectedTitleAIDs;
     var arr2 = SMState.SelectedTitleBIDs;
     
     var idx1 = $.inArray(id, arr1);
     var idx2 = $.inArray(id, arr2);
     if ( idx1 > -1 ) {
       arr1.splice( idx1, 1 );
     }
     if ( idx2 > -1 ) {
       arr2.splice( idx2, 1 );
     }
     this.updateListeners( {'type':'jobtype','data':id} );
   },
  'addJobTypeID' : function(id) {
    var id = parseInt(id);
    if ( SMState.SelectedJobTypeIDs.length < 2 ) {
      if ( $.inArray(id, SMState.SelectedJobTypeIDs) == -1 ) { 
        SMState.SelectedJobTypeIDs.push( id );
        this.updateListeners( {'type':'jobtype','data':id} );
      }
    }
   },
  'removeJobTypeID' : function(id) {
    var id = parseInt(id);
     var arr = SMState.SelectedJobTypeIDs;
     var idx = $.inArray(id, arr);
     if ( idx > -1 ) {
       // when you delete the first job type, the second becomes the first.
       if ( idx == 0 ) {
         SMState.SelectedTitleAIDs = SMState.SelectedTitleBIDs;
         SMState.SelectedTitleBIDs = [];
       } else {
         SMState.SelectedTitleBIDs = [];
       }
       arr.splice( idx, 1 );
       this.updateListeners( {'type':'jobtype','data':id} );
     }
   },
  'addLocationID' : function(id) {
    var id = parseInt(id);
    var l = this.SelectedCityIDs.length;

    if ( id == 263 || ( l == 1 && this.SelectedCityIDs[0] == 263 ) ) {
      this.removeAllLocationIDs();
    }
    
    if ( id != 263 ) {
      $('#workwhere2').trigger('click').trigger('updateState');
    }
    
    this.SelectedCityIDs.push( id );
    this.updateListeners( {'type':'location','data':id} );
 },
 'removeAllLocationIDs' : function(id){
   var id = parseInt(id);
   SMState.SelectedCityIDs = [];
   this.updateListeners( {'type':'location','data':id} );
 },
 'removeLocationID' : function(id) {
   var id = parseInt(id);
   var arr = SMState.SelectedCityIDs;
   var idx = $.inArray(id, arr);
   if ( idx > -1 ) {
     arr.splice( idx, 1 );
     this.updateListeners( {'type':'location','data':id} );
   }
 }
};

function changeSelections(event){
    
    switch (event.type) {
      case 'location' :
        var locationstate = $( '#locationstate' );
        try {
          
          locationstate.html( '' );
          
          var id = event.data;
          var i = 0;
          var l = SMState.SelectedCityIDs.length;
          var loc = {};
          var lastState = '';
          
          while ( i < l ) {
           loc = SMState.locations[SMState.SelectedCityIDs[i]];
           if ( i == 0 || lastState != loc.state ) {
            locationstate.append( '<li><strong>'+ loc.state + ':</strong> <span>' + loc.city + '</span></li>' );
            lastState = loc.state;
           } else {
            locationstate.children('li:last').append( ', <span>' + loc.city + '</span>' ); 
           }
           i++; 
          }
        } catch (e) {}
      break;
    case 'jobtype' :
      var titlestate1 = $( '#titlestate1' );
      var titlestate2 = $( '#titlestate2' );
      var types = SMState.SelectedJobTypeIDs;
      var titlesa = SMState.SelectedTitleAIDs;
      var titlesb = SMState.SelectedTitleBIDs;
      var i = 0;
      var l = types.length;
      var str = '';
      var cma = 0;
      
      titlestate1.html('<strong>Job Function 1:</strong>');
      titlestate2.html('<strong>Job Function 2:</strong>');
      
      while( i < l ) {
        if ( types[i] != 0 ) { 
          var arr = eval( 'a'+types[i] );
          if ( i == 0 ) {
            cma = 0;
            str = '<strong>Job Function 1:</strong> <span>'+arr[0]+' - </span>';
            var j = 0;
            var jl = arr[2].length;
            while ( j < jl ) {
              if ( $.inArray(parseInt(arr[2][j]), titlesa) > -1 ) {
                str += '<span>' + ( cma > 0 ? ', ' : '' ) + arr[1][j] + '</span>';
                cma = 1;
              }
              j++;
            }
            titlestate1.html( str );
          } else {
            cma = 0;
            str = '<strong>Job Function 2:</strong> <span>'+arr[0]+' - </span>';
            var j = 0;
            var jl = arr[2].length;
            while ( j < jl ) {
              if ( $.inArray(parseInt(arr[2][j]), titlesb) > -1 ) {
                str += '<span>' + ( cma > 0 ? ', ' : '' ) + arr[1][j] + '</span>';
                cma = 1;
              }
              j++;
            }
            titlestate2.html( str );
          }
        }
        i++;
      }
      break;
    case 'industry' :
      var industrystate = $( '#industrystate' );
      try {
        
        industrystate.html( '' );
        
        var id = event.data;
        var i = 0;
        var l = SMState.SelectedIndustryIDs.length;
        var ind = {};
        
        while ( i < l ) {
         ind = SMState.industrytypes[SMState.SelectedIndustryIDs[i]];
         if ( i > 0 ) {
          industrystate.append( ', ' ); 
         }
         industrystate.append( '<span>' + ind.shortindustrytype + '</span>' ); 
         i++; 
        }
      } catch (e) {}
      break;
    }
}

function showTitles(id, e) {
  var i = 0;
  var arr = eval( 'a'+id );
  var l = arr.length;
  var s = [];
  var e = e || window.event;
  var trg = e.target || e.srcElement;
  var li = $(trg.parentNode);
  
  var box = null;
  
  $( '.sublist' ).each( function(i){
    var el = $(this);
    el.hide();
    el.data('li').removeClass( 'sel' ).css('background-image','');
    
    if ( el.attr('title') == trg.title ) box = el;
  });
  
  var ts = SMState.SelectedJobTypeIDs;
  
  if ( ts.length >= 2 ) {
    var isthere = false;
    for( var t in ts ) {
      if ( ts[t] == id ) isthere = true; 
    }
    if ( !isthere ) return;
  }
  
  if ( !box ) {
      box = $(buildBox( id, arr ));
      box.attr( 'title', trg.title );
      var off = $(li).offset();
      box.css('top', off.top + li.height());
      box.css('left', off.left);
      box.css('z-index','20000');
      box.data( 'li', li );
      
      $('body').append(box);
    //var box = li.append( buildBox( id, arr ) );
  } else {
    box.show();
  }
  
  li.addClass( 'sel' );
}

function showCities( state, ev ) {
  var i = 0;
  var locs = SMState.locations;
  var s = [];
  var ev = ev || window.event;
  var trg = ev.target || ev.srcElement;
  var li = $(trg.parentNode);

  try {
    for( var p in locs ) {
      if ( locs.hasOwnProperty(p) ) {
        if ( locs[p].state && locs[p].state == state ) {
          s.push( locs[p] );
        }
      }
    }
    
    var box = null;
    
    $( '.sublist' ).each( function(i){
      var el = $(this);
      el.hide();
      el.data('li').removeClass( 'sel' ).css('background-image','');
      
      if ( el.attr('title') == trg.title ) box = el;
    });
    
    if ( !box ) {
      box = $(buildCityBox( state, s ));
      box.attr( 'title', trg.title );
      var off = $(li).offset();
      box.css('top', off.top + li.height());
      box.css('left', off.left);
      box.css('z-index','20000');
      box.data( 'li', li );
      
      $('body').append(box);
      //var box = li.append( buildCityBox( state, s ) );
    } else {
      box.show();
    }
    
    li.addClass( 'sel' );
    
  } catch (e) {alert(e.message)}
}

function beforeSubmit(form) {
  var industries = SMState.SelectedIndustryIDs;
  var cities = SMState.SelectedCityIDs;
  var titles1 = SMState.SelectedTitleAIDs;
  var titles2 = SMState.SelectedTitleBIDs;
  var jobtypes = SMState.SelectedJobTypeIDs;
  var selind = document.getElementById('ASelectedIndustryIDs');
  var selcity = document.getElementById('ASelectedCityIDs');
  var seltitlesa = document.getElementById('ASelTitleIDs_A');
  var seltitlesb = document.getElementById('ASelTitleIDs_B');
  var seljobtypes = document.getElementById('AJobFunctionTypeIDs');
  
  selind.value = industries.join();
  selcity.value = cities.join();
  seltitlesa.value = titles1.join();
  seltitlesb.value = titles2.join();
  seljobtypes.value = jobtypes.join();
  
  //var ww1 = $('#workwhere1');
  //if ( ww1.is( ':checked' ) ) selcity.value = ww1.attr('value');
  
  //var ind1 = $('#industry1');
  //if ( ind1.is( ':checked' ) ) selind.value = ind1.attr('value');
  
  if ( localjsValidateSpiderMatchForm() ) {
    return true;
  } else {
    return false;
  }
}

function buildBox( id, arr ) {
  
  box = $( '<div class="sublist"></div>' );
  var clink = $( '<a class="close">Close</a>' )
                  .click( function(e){
                      var p = $(this).parent();
                      p.data('li').removeClass('sel').css('background-image','');
                      p.hide();
                   } )
                  .appendTo(box);
  var list = $( '<ul></ul>' ).appendTo(box);
  var item, ctrl, lbl = null;
  var i = 0, j = 0;
  var l = arr[1].length;
  
  /*
  arr[1].sort(function ( a, b ) {
    var a = a.toLowerCase();
    var b = b.toLowerCase();
    return (a < b) ? -1 : (a > b) ? 1 : 0;
   });
   
  arr[2].sort(function ( a, b ) {
    return (a < b) ? -1 : (a > b) ? 1 : 0;
   });
  */
  
  var ttla = $('#ASelTitleIDs_A').attr('value').split(',');
  var ttlb = $('#ASelTitleIDs_B').attr('value').split(',');
  var ttls =  ( ttla && ttla.length && ttla[0] != '' ? ttla.concat(ttlb) : ttlb );
  var jl = ttls.length;
  
  while( i < l ) {
   var lbl = $('<label></label>');
   var chkd = '';
   while ( j < jl ) {
     if ( parseInt(arr[2][i]) == parseInt(ttls[j]) ) {
       chkd = ' checked="checked"';
     }
     j++;
   }
   j = 0;
   var ctrl = $('<input type="checkbox" name="jobtitle'+arr[2][i]+'" id="jobtitle'+arr[2][i]+'" value="' + arr[2][i] + '"' + chkd + ' />')
      .click( function(){ 
        
        var doIt = true;
        if ( $(this).is(':checked') ) {
          SMState.addJobTypeID(id);
          SMState.addTitleID(this.value, id);
          $(this).parents('.sublist').data('li').addClass('act'); 
        } else {
          SMState.removeTitleID(this.value);
          $(this).parents('.sublist ul').find('input').each(function(i){
            if ( $(this).is(':checked') ) {
              doIt = false;
              return;
            }
          });
          if (doIt) {
            SMState.removeJobTypeID(id);
            $(this).parents('.sublist').data('li').removeClass('act'); 
          }
        }
        
       } )
      .appendTo( lbl );
   $( '<span>' + arr[1][i] + '</span>' ).appendTo( lbl );
   var itm = $('<li></li>').appendTo( list );
   lbl.appendTo(itm);
   i++;
  }
  
  return box;
}

function buildCityBox( state, locs ) {  
  box = $( '<div class="sublist city"></div>' );
  var clink = $( '<a class="close">Close</a>' )
                  .click( function(e){
                      var p = $(this).parent();
                      p.data('li').removeClass('sel').css('background-image','');
                      p.hide();
                    } )
                  .appendTo(box);
  var list = $( '<ul></ul>' ).appendTo(box);
  var item, ctrl, lbl = null;
  var i = 0;
  var l = locs.length;
  var sci = $('#ASelectedCityIDs').attr('value');
  var scia = [];
  
  if ( typeof sci == 'string' && sci != '' ) {
    scia = sci.split(',');
  } else {
    scia = [];
  }
  
  var chkd = '';
  
  var lockeys = (function(){
    var arr = [];
    for ( var i in locs ) {
      if ( locs.hasOwnProperty(i) ) {
        if ( locs[i].city == 'All' ) {
          arr.unshift( parseInt(i) );
        } else {
          arr.push( parseInt(i) );
        }
      }
    }
    return arr;
  })();
  
  /*
  lockeys.sort(function ( a, b ) {
    return a - b;
   });
   */
    
  while( i < l ) {
   var lbl = $('<label></label>');
   chkd = '';
   for ( itm in scia ) {
     if ( parseInt(locs[lockeys[i]].cityid) == parseInt(scia[itm]) ) {
       chkd = ' checked="checked"';
       break;
     }
   }

   var ctrl = $('<input type="checkbox" value="'+locs[lockeys[i]].cityid+'"'+chkd+' />')
      .click( function(){ 
          var doIt = true;
          if ( $(this).is(':checked') ) {
            if ( $(this).siblings( 'span' ).text() == 'All' ) {
              $(this).parent().parent().nextAll().find( 'input:checked' ).each(function(i){
                SMState.removeLocationID(this.value);
                $(this).removeAttr( 'checked' );
              });
            } else {
              var itm = $(this).parent().parent().parent().find( 'li:first input' );
              if (itm) {
                itm.removeAttr( 'checked' );
                SMState.removeLocationID(itm.attr('value'));
              }
            }
            SMState.addLocationID(this.value);
            $(this).parents('.sublist').data('li').addClass('act');
          } else {
            SMState.removeLocationID(this.value);
            $(this).parents('.sublist').find('input').each(function(i){
              if ( $(this).is(':checked') ) {
                doIt = false;
                return;
              }
            });
            if (doIt) $(this).parents('.sublist').data('li').removeClass('act'); 
          }
        } )
      .appendTo( lbl );
   $( '<span>'+locs[lockeys[i]].city+'</span>' ).appendTo( lbl );
   var itm = $('<li></li>').appendTo( list );
   lbl.appendTo(itm);
   i++;
  }
  
  return box;
}

function addClass( el, cls ) {
  if (!el) return;
  
  var classes = el.className.split(' ');
  
  if ( hasClass( el, cls ) ) return;
  
  classes.push(cls);
  el.className = classes.join(' ');
}

function removeClass( el, cls ) {
  if (!el || !el.className) return;
  
  var classes = el.className.split(' ');
  var i = findClass( el, cls);
  
  if ( i > -1 ) classes.splice( i, 1 );
  
  el.className = classes.join(' ');
}

function findClass( el, cls ) {
  if (!el || !el.className) return -1;
  
  var classes = el.className.split(' ');
  var i = 0;
  var l = classes.length;
  
  while( i < l ) {
    if ( classes[i].toUpperCase() === cls.toUpperCase() ) {
      return i;
    }
    i++;
  }
  
  return -1;
}

function hasClass( el, cls ) {
  return findClass( el, cls ) > -1;
}

function roundify( sel, radius ) {
	if ( $.browser.msie )
  {
    DD_roundies.addRule( sel, radius );
  }
}

function sm_init() {    
  $('.selectlist.industry input[type=checkbox]').bind( 'click', function(){ 
        if ( $.inArray( parseInt(this.value), SMState.SelectedIndustryIDs ) > -1 || 
             SMState.SelectedIndustryIDs.length < 10 ) {
            if ( $(this).is(':checked') ) {
              $(this).siblings( 'span' ).addClass( 'act' ).css('background-image','');
              SMState.addIndustryID(this.value);
            } else {
              $(this).siblings( 'span' ).removeClass( 'act' ).css('background-image','');
              SMState.removeIndustryID(this.value);
            }
        }
      });
        
  $('#workwhere1').bind( 'click', function(){ 
    SMState.addLocationID(this.value) 
    $('#citylist li').removeClass('act');
    $('.sublist.city input[type=checkbox]').attr( 'checked', '' );
   } );
   
  $('#industry1').bind( 'click', function(){ 
    SMState.addIndustryID(this.value);
    $('.sublist.industry .act').removeClass('act');
    $('.sublist.industry input[type=checkbox]').attr( 'checked', '' );
   } );
  
  roundify( '.matchform', '0 0 20px 20px' );
  
  if ( $.browser.mozilla ) {
    $('.sidebar').css('margin-left','-55px');
  }
  
  if ( /chrome/.test( navigator.userAgent.toLowerCase() ) ) {
    $('.sidebar').css('top','0');
    $('#industrysidebar,#jobsidebar').css('margin-top','30px');
  }
  
  SMState.addListener( changeSelections );
  
  // load existing location selections...
  (function(){
    var sci = $('#ASelectedCityIDs').attr('value');
    var scia = [];
    
    if ( typeof sci == 'string' && sci != '' ) {
      scia = sci.split(',');
      for( var itm in scia ) {
        SMState.addLocationID( scia[itm] );
      }
  }})();
  
  // load existing job types selections...
  (function(){
    var sci = $('#ASelTitleIDs_A').attr('value');
    var types = $('#AJobFunctionTypeIDs').attr('value').split(',');
    var scia = [];
    
    if ( typeof sci == 'string' && sci != '' ) {
      scia = sci.split(',');
      for( var itm in scia ) {
        SMState.addJobTypeID( types[0] );
        SMState.addTitleID( scia[itm], types[0] );
      }
  }})();
  
  // load existing job types selections...
  (function(){
    var sci = $('#ASelTitleIDs_B').attr('value');
    var types = $('#AJobFunctionTypeIDs').attr('value').split(',');
    var scia = [];

    if ( typeof sci == 'string' && sci != '' && types && types.length > 1 ) {
      scia = sci.split(',');
      for( var itm in scia ) {
        SMState.addJobTypeID( types[1] );
        SMState.addTitleID( scia[itm], types[1] );
      }
  }})();
  
  // load existing industry selections...
  (function(){
    var sci = $('#ASelectedIndustryIDs').attr('value');
    var scia = [];
    
    if ( typeof sci == 'string' && sci != '' ) {
      scia = sci.split(',');
      for( var itm in scia ) {
        SMState.addIndustryID( scia[itm] );
      }
  }})();
  
  
  $('label.chk input, label.rad input').each(function(i){
    var input = $(this);
    var label = $('label[for=' + input.attr('id') + ']');
    var span = label.find('.label');
    var allInputs = $('input[name=' + input.attr('name') + ']');
    var inputType = (input.is('[type=checkbox]')) ? 'checkbox' : 'radio';
    
    label.hover( function(){ $(this).toggleClass('hvr'); },
                 function(){ $(this).toggleClass('hvr'); });

  	input.bind('updateState', function(){
			if (input.is(':checked')) {
				if (input.is(':radio')) {				
					allInputs.each(function(){
						$('label[for='+$(this).attr('id')+']').removeClass('clk');
						span.css('background-image','');
					});		
				};
				label.addClass('clk');
				span.css('background-image','');
			}
			else { label.removeClass('clk hvr fcs');span.css('background-image',''); }
									
			})
			.trigger('updateState')
			.click(function(){ $(this).trigger('updateState') })
			.focus(function(){ 
				label.addClass('fcs'); 
				if(inputType == 'checkbox' && input.is(':checked')){ 
					$(this).addClass('fcs'); 
				} 
			})
			.blur(function(){ label.removeClass('fcs'); });          
  });
}


$(document).ready(sm_init);

