"use strict";
/*global Router, FormValidator,AjaxUpload*/
/*jslint white: true, devel: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: true, maxerr: 50, indent: 2 */
var EK = EK || {};

EK.ProviderDirectory = {
  timeout: null,
  routes: [{
    pattern: /^request$/,
    action: function (hash) {
      EK.ProviderDirectory.requestProviderInformation(hash);
    }
  }],
  init: function () {
    this.bind();
    Router.add(this.routes);
    this.initFirstVisitPopup();
  },
  bind: function () {
    var t = this;
    $('.request-provider-information').live('click', function () {
      t.requestProviderInformation();
    });
    $('.contact_provider_form').bindSubmit({
      beforeSubmit: EK.ProviderDirectory.beforeSubmit,
      success: EK.ProviderDirectory.success,
      data: [{
        name: 'form-fields',
        value: JSON.stringify(["form-subject-add", "message"])
      }]
    });
    $('.send_btns').live('click', function () {
      $('.contact_provider_form').trigger('submit');
    });
  },
  beforeSubmit: function () {
    try {
      return true;
    } catch (e) {
      return false;
    }
  },
  checkFields: function () {
    var fields = {
      'form-subject-add' : 'Subject',
      'message'  : 'Message'
    };
    FormValidator.checkFields(fields);
  },
  success: function (xhr) {
    $('#req_step_01, #req_step_02').toggle();
    EK.ProviderDirectory.resetForm();

    EK.ProviderDirectory.timeout = window.setTimeout(function () {
      EK.ProviderDirectory.onClose();
    }, 3000);
  },
  resetForm: function () {
    $('#provider_request_subject').val('');
    $('#provider_request_message').html('');
  },
  onClose: function () {
    $('#req_step_01, #req_step_02').toggle();
    $.modal.close();
    window.location.replace('#');
    window.clearTimeout(EK.ProviderDirectory.timeout);
  },
  requestProviderInformation: function () {
    var popupOptions = {
      close : true,
      escClose : true,
      overlayCss : { backgroundColor : 'black' },
      closeClass : 'sglg_close',
      onClose: function () {
        EK.ProviderDirectory.onClose();
      }
    };
    var $el = $('#contact_provider');
    if ($el.length) {
      $el.modal(popupOptions);
    }
  },
  initFirstVisitPopup: function() {
	  if((document.cookie + '').indexOf('provider_directory_first_visit=false') == -1) {
		$.getJSON('/provider-directory/api/utils/first_visit', {_:(new Date()).getTime()}, function(data) {
			if(data){
				var popupOptions = {
					close : true,
					closeHTML: null,
					closeClass: 'continue',
					escClose : true,
					overlayCss : { backgroundColor : '#000' },
					onClose: function (dialog) {
						if($('#popup_first_visit input:checkbox').attr('checked')){
							$.ajax({url : '/provider-directory/api/utils/don_t_show_provider_directory_popup', cache: false});
						}
						$.modal.close();
					}
				};
				$('#popup_first_visit').width(628);
				$('#popup_first_visit').modal(popupOptions);
			}
		});
  	}
  }
};
EK.ProviderDirectory.Rate = {
  init: function () {
    this.bind();
  },
  bind: function () {
    $('.rate-helpful a, .rate-nothelpful a').live('click', function () {
      if ($(this).hasClass('type-on')) {
        return false;
      }
    });
  }
};

EK.ProviderDirectory.UploadForm = {
  pluginEl: null,
  hasFile: false,
  container: '#provider-upload-logo',

  init: function () {
    this.bind();
  },

  bind: function () {
    this.bindPopup();
    this.bindButtons();
  },

  bindPopup: function () {
    var t = this;

    var popupOptions = {
      close : true,
      escClose : true,
      overlayCss : { backgroundColor : 'black' },
      closeClass : 'sglg_close',
      onClose: function () {
        $.modal.close();
        //we need to remove fake input's on close or they will miltiply
        $('input[type="file"]').filter('[name="name"]').parent().remove();
      },
      onShow: function () {
        t.initPlugin.call(t);
      }
    };

    $('.company-info .company-logo, .company-info .edit-field-btn').live('click', function () {
      $(t.container).modal(popupOptions);
    });
  },

  bindButtons: function () {
    var t = this;
    $('.upload_btns .cancel').live('click', function () {
      $.modal.close();
    });
    $('.upload_btns .commit').live('click', function () {
      t.pluginEl.submit();
    });
  },

  isValid: function () {
    return this.hasFile;
  },

  initPlugin: function () {
    var t = this;

    this.hasFile = false;
    this.pluginEl = new AjaxUpload('upload-file-container', {
      action: '/provider-directory/upload_logo',
      name: 'file',
      autoSubmit: false,
      onChange: function (file, ext) {
        $('#fileInputText').html(file);
        this.hasFile = file !== 'undefined';
      },
      onSubmit : function (file, ext) {
        t.providerId = $('#provider-id').html() || 0; 

        this.disable();
        this.setData({
          profile_id: t.providerId 
        });

        $(t.container).find('.state-default,.state-success').hide();
        $(t.container).find('.state-upload').show();
      },
      onComplete : function (file) {
        $(t.container).find('.state-default,.state-upload').hide();
        $(t.container).find('.state-success').show();

        window.setTimeout(function () {
          $.modal.close();

          $('#logo-display').html('<img src="/provider-directory/serve_logo/' + t.providerId + '?width=100&height=60&' + new Date().getTime() + '" />');
          $('#logo-preview').html('<img src="/provider-directory/serve_logo/' + t.providerId + '?width=100&height=60&' + new Date().getTime() + '" />');
        }, 4000);
      }
    });
  }
};
EK.ProviderDirectory.Notification = {
  init: function () {
    var $el = $("#review-message");
    if ($el.length) {
      window.setTimeout(function () {
        $el.hide();
      }, 10000);
    }
  }
};
EK.ProviderDirectory.ListInfoPopup = {
	init : function() {
		$('.list-popup-show').each(function(){
			var a = $(this);
			a.mouseover(function(){
				var el = $(this);
				var pos = el.offset();
				var html = $(document.documentElement);
				var height = html.height();
				var top = pos.top - html.scrollTop();
				var popup = el.nextAll('.list_popup');
				var pHead = popup.find('div:first');
				var pFoot = popup.find('div:last');
				if ((height-top) < height/2 ) {
					popup.css({
						top: 'auto',
						bottom: '15px'
					});
					pHead.removeClass('top_arrow');
					pHead.addClass('top');
					pFoot.removeClass('bottom');
					pFoot.addClass('bottom_arrow');
				}
				else {
					popup.css({
						bottom: 'auto',
						top: '15px'
					});
					pHead.removeClass('top');
					pHead.addClass('top_arrow');
					pFoot.removeClass('bottom_arrow');
					pFoot.addClass('bottom');
				}
				el.nextAll('.list_popup').show();
			});
			a.mouseout(function(){
				$(this).nextAll('.list_popup').hide();
			});
		});
	}
};
EK.ProviderDirectory.SolutionProfileExpandCollapse = {
	init : function() {
		$('.collapse-expand').click(function() {
			var plus_minus = $(this);
			var content = plus_minus.parents('.profile_categories').nextAll('.categ_fields:first');
			if(plus_minus.hasClass('collapsed')) {
				plus_minus.removeClass('collapsed');
        
        content.slideDown('slow', function() {
					plus_minus.attr('title', 'Collapse');
				});
			}
			else {
				plus_minus.addClass('collapsed');
        
        content.slideUp('slow', function() {
					plus_minus.attr('title', 'Expand');
				});
			}

      EK.ProviderDirectory.SolutionProfileExpandCollapse.hide_expand_collapse_all();
		  
      return true;
    });
    
    $('#expand_all').click(function(){
      $('.collapse-expand').each(function(index){
        var plus_minus = $(this);
        var content = plus_minus.parents('.profile_categories').nextAll('.categ_fields:first');
        if(plus_minus.hasClass('collapsed')) {
          plus_minus.removeClass('collapsed');
          
          content.slideDown('fast', function() {
            plus_minus.attr('title', 'Collapse');
          });
        }
      });

     EK.ProviderDirectory.SolutionProfileExpandCollapse.hide_expand_collapse_all();
    
     return true;
    });

    $('#collapse_all').click(function(){
      $('.collapse-expand').each(function(index){
        var plus_minus = $(this);
        var content = plus_minus.parents('.profile_categories').nextAll('.categ_fields:first');
        if(!plus_minus.hasClass('collapsed')) {
					plus_minus.addClass('collapsed');
          
          content.slideUp('fast', function() {
					  plus_minus.attr('title', 'Expand');
				  });
        }
      });

     EK.ProviderDirectory.SolutionProfileExpandCollapse.hide_expand_collapse_all();
    
     return true;
    });


		$('.collapse-expand:not(:first)').trigger('click');
	},

  hide_expand_collapse_all : function(){
    var all_collapsed = true;
    var all_expanded = true;

    $('.collapse-expand').each(function(index){
      if($(this).hasClass('collapsed')){
        all_expanded = false;      
      }else{
        all_collapsed = false;
      }
    });

    if(all_collapsed){
      $('#collapse_all').hide();
    }else{
      $('#collapse_all').show();
    }

    if(all_expanded){
      $('#expand_all').hide();
    }else{
      $('#expand_all').show();
    }
  }
};
EK.ProviderDirectory.ProviderCompanies = {
	init : function() {
		$('ul.alph_sorted_list>li').hoverIntent(function() {
			var el = $(this);
			var viewFProfBtn = el.find('.view_fprof');
			var content = el.find('.list_inline');
			if (content.css('display') == 'none') {
				var ul = el.parent();
				ul.css({
					height: ul.height()+'px',
					overflow: 'hidden'
				});
				ul.find('.list_inline').slideUp('fast');
				ul.find('.view_fprof').hide();
				content.height(66);
				content.slideDown('fast', function() {
					$(this).css('height','');
					ul.css({
						height: '',
						overflow: ''
					});
				});
				viewFProfBtn.show();
			}
		}, function() {});

	}
};

EK.ProviderDirectory.ProviderCategories = {
	init : function() {
		$('#provider-list ul.alph_sorted_list li').hoverIntent(function() {
			var el = $(this);
			var content = el.find('.list-catagory');
			if (content.css('display') == 'none') {
				el.parents('#provider-list').find('.list-catagory').slideUp('fast');
				content.slideDown('fast');
			}
		}, function() {});
	}
};

$(function() {
	if (/provider-directory/.test(window.location.pathname)) {
		EK.ProviderDirectory.init();
		EK.ProviderDirectory.Rate.init();
		EK.ProviderDirectory.UploadForm.init();
	}
	if (/provider-directory\/solution/.test(window.location.pathname)) {
		EK.ProviderDirectory.SolutionProfileExpandCollapse.init();
	}
	if (/provider-directory\/alphabetical\/solutions/.test(window.location.pathname)) {
		EK.ProviderDirectory.ListInfoPopup.init();
	}
	if ((/provider-directory\/alphabetical\/providers/.test(window.location.pathname)) || (/provider-directory\/by_category\/providers\/.+/.test(window.location.pathname)))  {
		EK.ProviderDirectory.ProviderCompanies.init();
	}
	if ((/provider-directory\/by_category\/providers\/?$/.test(window.location.pathname)) || (/provider-directory\/by_category\/solutions/.test(window.location.pathname))) {
		EK.ProviderDirectory.ProviderCategories.init();
	}
});

