// JQuery Plugin for ACT Site code lookup
// FSJ 2009-07-07
// Requies jQuery 1.3.2+
// Requires jQuery json.js plugin: www.liquidgear.net
(function($) {

    $.fn.extend({


		/* 
		Given an account number, set the site.
		We'll also need to pull down all the sites for the city, and the cities in the state.
		*/
		setaccountnumber: function(acctnum){
		
		// if the account number is 99999, set the city from the school, and set the site field to MY 
		// SITE IS NOT LISTED
			
			//if the account number exists in the current site dropdown, set it and exit
			
			var samecity = false;
			$(this).find('select:eq(2) option').each(function() {
				
				//console.log($(this).text(), $(this).attr('value'), $(this).data('account_num'), acctnum);
				if ($(this).data('account_num') == acctnum) {
					$(this).attr({'selected': 'selected'});
					samecity = true;
					return false; // break the loop
				}
			});
			// done; exit the fn
			if (samecity) {
				return true;	
			}else{
				/* Fetch the customer number details from the site cache */
				
				var cust_info = $(this).find('select:eq(2)').data(acctnum)
				//console.log(cust_info);
				
				// we need to make the ajax calls syncronous here
				$.ajaxSetup({async: false});
				//set the new city
				$(this).find('select:eq(1) option[value='+cust_info.city+']').attr({'selected': 'selected'}).trigger('change');
				
				// set the right customer, waiting for the ajax to complete
				//console.log($(this).find('select:eq(2) option'));
			
			
				$(this).find('select:eq(2) option[value='+cust_info.site_code+']').attr({'selected': 'selected'}).trigger('change');
		
				$.ajaxSetup({async: true});
				
			}			
		},
			
		getsitecode: function(id){
			return $(this).find('select:eq(2)').val();	
		},
	
		sitecodetable: function(options){
			var defaults = {
                
				entryType: 'dropdown', //How the user enters what they want: dropdown, typeahead
                url: 'sitecodes.php',
                program: 'EXPL', // OPTIONS: PLAN, EXPL
				prefix: 'sitecodetable_',
				showSiteCodeField: false

            }
			
            var options = $.extend(defaults, options);

            return this.each(function() {
                var o = options;

				var fields = ['State', 'City'];
                var ol = $('<ol></ol>');
				var topelem=$(this);
				
                $.each(fields,
                function(i) {
                    var f = this.toLowerCase();

                    var sel = $('<select></select>').attr({
                        'name': o.prefix + f,
                        'id': o.prefix + f,
                        'size': 1
                    }).css({'width':'200px'});
					if (i!=0) {
						sel.attr({'disabled':'disabled'});
					};
					
                    var lab = ($('<label>' + this + '</label>').attr({
                        'for': o.prefix + f
                    }));
					var err = ($('<strong></strong>').attr({
						'class':'error',
						'id': 'error_' + sel.attr('id')
					}));
					var img = $('<span></span>').attr({
						'id':o.prefix + f + '_msg'
					});
                    var li = $('<li></li>').addClass('float_left');
					lab.append(err);
                    li.append(lab);
                    li.append(sel);
					li.append(img);
                    ol.append(li);
					
                });
				ol.append('<li class="clear_left">	\
				<table id='+o.prefix+'table border="0" cellspacing="5" cellpadding="5">  \
					<caption>PLAN/EXPLORE Site Codes</caption>	\
					<thead><tr>		                               \
						<th>Site Name</th>                              \
						<th>PLAN</th>                              \
						<th>EXPLORE</th>                           \
						</tr>                                      \
						</thead>                    			 \
					<tbody><tr><td>&nbsp;</td>	 \
						<td>&nbsp;</td>                        \
						<td>&nbsp;</td>                          \
					</tr>                       \
					</tbody> \
				</table></li>');
				
				$(this).append(ol);
				
				// get the list of states
                $.ajax({
                    url: o.url,
					cache: true,
                    type: 'post',
                    //contentType: "application/x-www-form-urlencoded",
                    data: '{"method":"getStates"}',
					beforeSend: function(xhr) {
						$('#'+o.prefix + 'state_msg').empty().append($('<img></img>').attr({
							'src':'images/ajax-loader.gif',
							'alt':'Loading data...'
						}));
					},
                    success: function(data, status) {
                        //console.log("Success!!");
                        //console.log(data);
                        //console.log(status);
						$('#'+o.prefix + 'state').append($('<option>Select a state...</option>').attr({'value':'','selected':'selected'}));
						$('#'+o.prefix + 'state_msg img').remove();
                        var jsondata = $.json.decode(data);
                        //console.log(jsondata);
                        $.each(jsondata,
                        function() {
                            //console.log(this);
                            $('#'+o.prefix + 'state').append($('<option>' + this.fullname + '</option>').attr({
                                'value': this.state
                            }));
                        });

                    },
                    error: function(xhr, desc, err) {
                        //console.log(xhr);
                        //console.log("Desc: " + desc + "\nErr:" + err);
						$('#'+o.prefix + 'state_msg img').attr({
							'src':'images/delete_btn.png'
						});
                    }
                });

				// get the list of cities
                $('#'+o.prefix + 'state').change(function() {

	                    $.ajax({
	                        url: o.url,
	                        type: 'post',
							cache: true,
	                        contentType: "application/x-www-form-urlencoded",
	                        data: '{"method":"getCitiesInState","params":{"state":"' + $('#'+o.prefix + 'state').val() + '"}}',
							beforeSend: function(xhr) {
								$('#'+o.prefix + 'state_msg').empty().append($('<img></img>').attr({
									'src':'images/ajax-loader.gif',
									'alt':'Loading data...'
								}));
							},
	                        success: function(data, status) {
	                            //console.log("Success!!");
	                            //console.log(data);
	                            //console.log(status);
								$('#'+o.prefix + 'state_msg img').remove();
	                            $('#'+o.prefix + 'city,'+o.prefix + 'site').children('option').remove();
								//$('#'+o.prefix + 'results').html('');
	                            $('#'+o.prefix + 'city').removeAttr('disabled');
								$('#'+o.prefix + 'city').append($('<option>Select a city...</option>').attr({'value':'','selected':'selected'})).data('sitecode',' ');
								var jsondata = $.json.decode(data);
	                            $.each(jsondata,
	                            function() {
	                                //console.log(this);

	                                $('#'+o.prefix + 'city').append($('<option>' + this.city + '</option>').attr({
	                                    'value': this.city
	                                }));
	                            });

	                        },
	                        error: function(xhr, desc, err) {
	                            $('#'+o.prefix + 'state_msg img').attr({
									'src':'images/delete_btn.png'
								});
	                        }
	                    });

                });
				
				// list the site codes
                $('#'+o.prefix + 'city').change(function() {
                    $.ajax({
                        url: o.url,
                        type: 'post',
						cache: true,
                        contentType: "application/x-www-form-urlencoded",


                        data: '{"method":"getSiteCodesForCity","params":{"state":"' + $('#'+o.prefix + 'state').val() + '","city":"'+$('#'+o.prefix + 'city').val()+'"}}',
                        beforeSend: function(xhr) {
							$('#'+o.prefix + 'city_msg').empty().append($('<img></img>').attr({
								'src':'images/ajax-loader.gif',
								'alt':'Loading data...'
							}));
						},
						success: function(data, status) {
                            //console.log("Success!!");
                            //console.log(data);
                            //console.log(status);
							$('#'+o.prefix + 'city_msg img').remove();
							$('#'+o.prefix + 'table tbody tr').remove();
                            var jsondata = $.json.decode(data);
                            //console.log(jsondata);
                           
                            $.each(jsondata,
                            function() {
                                //console.log(this)
								var tr = $('<tr></tr>');
								tr.append('<td>'+this.account_name+'</td><td>'+this.plan_site_code+'</td><td>'+this.expl_site_code+'</td>')
								$('#'+o.prefix+ 'table tbody').append(tr);
                            });
							// Change the color of odd rows
							$('#'+o.prefix+ 'table tbody tr:odd').addClass('next');

                        },
                        error: function(xhr, desc, err) {
                            $('#'+o.prefix + 'city_msg img').attr({
								'src':'images/delete_btn.png'
							});
                        }
                    });

                });

				//clear table after ajax calls
				$('#'+o.prefix + 'table').ajaxStart(function() {
					$(this).find('tbody tr').remove();
					$('#'+o.prefix + 'table tbody').append('<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>')
					
				});
			});
		},

/////////////////////////////////////////////////////////////////////////////////////
        //pass the options variable to the function
        sitecodelookup: function(options) {


            //Set the default values, use comma to separate the settings, example:
            var defaults = {
                
				entryType: 'dropdown', //How the user enters what they want: dropdown, typeahead
                url: 'sitecodes.php', // url of the sitecodes web service
                program: 'EXPL', // OPTIONS: PLAN, EXPL
				prefix: 'sitecodelookup_', // prefix all fields with this
				//showSiteCodeField: false, // 
				initialState: null // start with this state

            }

            var options = $.extend(defaults, options);
			var _this = $(this);

            return this.each(function() {
                var o = options;

                //code to be inserted here
                //you can access the value like this
                //alert(o.showSiteCodeField);
                //Add the HTML to the DIV
                var fields = ['State', 'City', 'Site'];
                var ol = $('<ol></ol>');
				var topelem=$(this);
				
				//add sitecode lookup class
				$(this).addClass("sitecodelookup");
				
                $.each(fields,
                function(i) {
                    var f = this.toLowerCase();

                    var sel = $('<select></select>').attr({
                        'name': o.prefix + f,
                        'id': o.prefix + f,
						'class': 'sitecodelookup',
                        'size': 1
                    }).css({'width':'200px'});
					if (i!=0) {
						sel.attr({'disabled':'disabled'});
					};
					
                    var lab = ($('<label>' + this + ' </label>').attr({
                        'for': o.prefix + f
                    }));
					var err = ($('<strong></strong>').attr({
						'class':'error',
						'id': 'error_' + sel.attr('id')
					}));
					var img = $('<span></span>').attr({
						'id':o.prefix + f + '_msg'
					});
                    var li = $('<li></li>').addClass('clear_left');

					lab.append(err);
                    li.append(lab);
                    li.append(sel);
					li.append(img);
                    ol.append(li);
					
                });
				//make the first 2 fields in line, instead of on top of each other
				ol.children('li:not(:last)').removeClass('clear_left').addClass('float_left');
				$(this).append(ol);
				//site code field
				var inp = ($('<input type="text"></input>').attr({
					id:o.prefix + 'sitecode',
					name:o.prefix + 'sitecode',
					disabled:'disabled',
					readonly:'readonly'
				}));
				
				var lab = ($('<label>Site Code</label>').attr({
                    'for': o.prefix + 'sitecode'
                }));
				var li = $('<li></li>').addClass('clear_left');
				li.append(lab);
				li.append(inp);
			
				ol.append(li);
				if(!o.showSiteCodeField){
					$('#'+o.prefix+'sitecode').parent('li').hide();
				}

                // get the list of states
                $.ajax({
                    url: o.url,
					cache: true,
                    type: 'post',
                    //contentType: "application/x-www-form-urlencoded",
                    data: '{"method":"getStates", "program":"'+o.program+'"}',
					beforeSend: function(xhr) {
						$('#'+o.prefix + 'sitecode, #'+o.prefix + 'site').empty().val('').trigger('change');
						$('#'+o.prefix + 'state_msg').empty().append($('<img></img>').attr({
							'src':'images/ajax-loader.gif',
							'alt':'Loading data...'
						}));
					},
                    success: function(data, status) {
                        //console.log("Success!!");
                        //console.log(data);
                        //console.log(status);
						_this._setstates(data, o.prefix);
						
						//jump through hurdles for IE6
						if (o.initialState != null) {
							try{
								$('#'+o.prefix + 'state option').removeAttr('selected');
								$('#'+o.prefix + 'state option[value="'+o.initialState+'"]').attr({'selected':'selected'});
								$('#'+o.prefix + 'state').trigger('change');
								
							}
							catch(ex){
								//for ie6, wait 10 ms before trying to set the selected state
								setTimeout(function() {
									$('#'+o.prefix + 'state option').removeAttr('selected');
									$('#'+o.prefix + 'state option[value="'+o.initialState+'"]').attr({'selected':'selected'});
									$('#'+o.prefix + 'state').trigger('change');
									
								}, 10);
								
							}

							
						};

                    },
                    error: function(xhr, desc, err) {
                        //console.log(xhr);
                        //console.log("Desc: " + desc + "\nErr:" + err);
						$('#'+o.prefix + 'state_msg img').attr({
							'src':'images/delete_btn.png'
						});
                    }
                });
				// get the list of cities
                $('#'+o.prefix + 'state').change(function() {
			
	                    $.ajax({
	                        url: o.url,
	                        type: 'post',
							cache: true,
	                        contentType: "application/x-www-form-urlencoded",
	                        data: '{"method":"getCitiesInState","program":"'+o.program+'","params":{"state":"' + $('#'+o.prefix + 'state').val() + '"}}',
							beforeSend: function(xhr) {
								$('#'+o.prefix + 'sitecode, #'+o.prefix + 'site').empty().val('').trigger('change');
								$('#'+o.prefix + 'state_msg').empty().append($('<img></img>').attr({
									'src':'images/ajax-loader.gif',
									'alt':'Loading data...'
								}));
							},
	                        success: function(data, status) {
	                            //console.log("Success!!");
	                            //console.log(data);
	                            //console.log(status);
								
								_this._setcities(data, o.prefix);

	                        },
	                        error: function(xhr, desc, err) {
	                            $('#'+o.prefix + 'state_msg img').attr({
									'src':'images/delete_btn.png'
								});
	                        }
	                    });
					
                });
				// get the list of sites
                $('#'+o.prefix + 'city').change(function() {
					if($('#'+o.prefix + 'city').val() != 99999){
						$.ajax({
							url: o.url,
							type: 'post',
							cache: true,
							contentType: "application/x-www-form-urlencoded",


							data: '{"method":"getAccountsInCityState","program":"' + o.program + '","params":{"state":"' + $('#'+o.prefix + 'state').val() + '","city":"'+$('#'+o.prefix + 'city').val()+'"}}',
							beforeSend: function(xhr) {
								$('#'+o.prefix + 'sitecode, #'+o.prefix + 'site').empty().val('').trigger('change');
								$('#'+o.prefix + 'city_msg').empty().append($('<img></img>').attr({
									'src':'images/ajax-loader.gif',
									'alt':'Loading data...'
								}));
							},
							success: function(data, status) {
								
								
								_this._setsites(data, $('#'+o.prefix + 'city').val(),$('#'+o.prefix + 'state').val(), o.prefix);

								var selectedoption = ($('#'+o.prefix + 'site option').length == 2) ? $('#'+o.prefix + 'site option:nth-Child(2)') : $('#'+o.prefix + 'site option:first');
								// if there's only one result, go ahead and select it
								// checking number of options instead
									try	{
										selectedoption.attr({'selected':'selected'});
									}
									catch(e) {}
								
								 
								 $('#'+o.prefix + 'site').trigger('change');
								 $('#'+o.prefix + 'site').append($('<option>MY SITE IS NOT LISTED HERE</option>').attr({
																 'value': '99999'
															 }).data('account_num', '99999'));
							
							},
							error: function(xhr, desc, err) {
								$('#'+o.prefix + 'city_msg img').attr({
									'src':'images/delete_btn.png'
								});
							}
						});

				
				}else{
					$('#'+o.prefix + 'site option').remove();
					$('#'+o.prefix + 'site').removeAttr('disabled');
					$('#'+o.prefix + 'site').append($('<option>Select a site...</option>').val(-1).data('account_num', -1));
					$('#'+o.prefix + 'site').append($('<option>MY SITE IS NOT LISTED HERE</option>').attr({
																 'value': '99999'
															 }).data('account_num', '99999'));
					try	{
						$('#'+o.prefix + 'site option:last').attr({'selected':'selected'});
					}
					catch(e) {}
					$('#'+o.prefix + 'site').trigger("change");
				}
				});
				//show the site code
				$('#'+o.prefix + 'site').change(function() {
					$('#'+o.prefix + 'sitecode').val($('#'+o.prefix + "site option:selected").val());
				});
				

            });
        },
    
		_setstates: function(data, prefix){
				$('#'+prefix + 'state').append($('<option>Select a state...</option>').attr({'value':''})).data('sitecode',' ');
				$('#'+prefix + 'state_msg img').remove();
                var jsondata = $.json.decode(data);
                //console.log(jsondata);
                $.each(jsondata,
                function() {
                    //console.log(this);
                    $('#'+prefix + 'state').append($('<option>' + this.fullname + '</option>').attr({
                        'value': this.state
                    }));
                });

			
			return true;
		},
		_setcities: function(data, prefix){
			
			//store the cities away for future use
			$('#'+prefix + 'city').data($('#'+prefix + 'state').val(),data)
			
			$('#'+prefix + 'state_msg img').remove();
			$('#'+prefix + 'city, #'+prefix + 'site').children('option').remove();
			//$('#'+prefix + 'results').html('');
            $('#'+prefix + 'city').removeAttr('disabled');
			$('#'+prefix + 'city').append($('<option>Select a city...</option>').attr({'value':'','selected':'selected'}));
			var jsondata = $.json.decode(data);
            $.each(jsondata,
            function() {
                //console.log(this);
				if(this.city == 99999){
					$('#'+prefix + 'city').append($('<option>MY CITY IS NOT LISTED HERE</option>').attr({
						'value': this.city
					}));
				}else{
					$('#'+prefix + 'city').append($('<option>' + this.city + '</option>').attr({
						'value': this.city
					}));
				}
            });
            
			return true;
		},
		_setsites: function(data, incity, instate, prefix){
	
			$('#'+prefix + 'city_msg img').remove();
			//console.log("IN set sites");
            //console.log(data);
            //console.log(status);
		
            var jsondata = $.json.decode(data);
			//             console.log(jsondata);
			// console.log(prefix);
			// console.log('#'+prefix + 'site');
			// console.log($('#'+prefix + 'site'));
            $('#'+prefix + 'site option').remove();
            $('#'+prefix + 'site').removeAttr('disabled');
			$('#'+prefix + 'site').append($('<option>Select a site...</option>').val(-1).data('account_num', -1));
            $.each(jsondata,
            function() {
                //console.log(this)
                $('#'+prefix + 'site').append($('<option>' + this.account_name + '</option>').attr({
                    'value': this.site_code
                }).data('account_num', this.customer_num));
				//store the data away for future use
				$('#'+prefix+'site').data(this.customer_num, {account_name: this.account_name, site_code: this.site_code, city: incity, state:instate })
            });

		}


});

})(jQuery);


