var GeoLocate = function (timezone, cityPrecision, objectVar) {

  this.api = (cityPrecision) ? "ip_query.php" : "ip_query_country.php";
  this.domain = 'api.ipinfodb.com/v2';
  this.url = "http://" + this.domain + "/" + this.api + "?output=json" + ((timezone) ? "&timezone=true" : "&timezone=false" )
      + "&callback=" + objectVar + ".setGeoCookie" + "&key=b0eb6c47480ecd114234c3ee71d418108604e5e19488c19171ea46c6bd95e8b3";
  this.geodata;
  this.callbackFunc;
  this.cookieName = 'geolocation';            
};
//Check if cookie already exist. If not, query IPInfoDB
GeoLocate.prototype = {
  checkCookie : function(callback) {
    var cookieVal = this.getCookie();
    this.callbackFunc = callback;
    if (!cookieVal) {
      this.getGeolocation();
    } else {

      this.geodata = JSON.parse(cookieVal);
      this.callbackFunc();
    }
  },
  //API callback function that sets the cookie with the serialized JSON answer
  setGeoCookie : function(answer) {
    if (answer['Status'] == 'OK') {
      $.cookie(this.cookieName, JSON.stringify(answer), { expires: 30 });
      this.geodata = answer;
      this.callbackFunc();
    }
  },
  //Return a geolocation field
  getField: function(field) {
    try {
      return this.geodata[field];
    } catch(err) {
    }
  },
  getIp:function() {
    return this.geodata['Ip'];
  },
  getCountryCode:function() {
    return this.geodata['CountryCode'];
  },
  getCountryName:function() {
    return this.geodata['CountryName'];
  },
  getRegionCode:function() {
    return this.geodata['RegionCode'];
  },
  getCity:function() {
    return this.geodata['City'];
  },
  getZipPostalCode:function() {
    return this.geodata['ZipPostalCode'];
  },
  getRegionName:function() {
    return this.geodata['RegionName'];
  },
  getLatitude:function() {
    return this.geodata['Latitude'];
  },
  getLongitude:function() {
    return this.geodata['Longitude'];
  },
  getArray:function() {
    return this.geodata;
  },
  //Request to IPInfoDB
  getGeolocation:function() {
    try {
      var script = document.createElement('script');
      script.src = this.url;
      document.body.appendChild(script);
    } catch(err) {
    }
  }
  ,
  getCookie : function () {
    //return Ext.util.Cookies.get(this.cookieName);
    return $.cookie(this.cookieName)
  }
};

$(document).ready(function() {
  Cufon.replace('a.navitem', {fontFamily: 'Bebas', hover: true});
  var currNavIdentifier = $(".nav-identifier");
  if (currNavIdentifier && currNavIdentifier.length > 0)
  {
    currNavId = "#" + currNavIdentifier[0].id.replace(/_navitem$/, "");
    $(currNavId).addClass("navitem2");
    //    Cufon.refresh();
  }

  //Primary nav bar's drop down menu
  $(".nav-level-1").mouseover(function() {
    var dh = $(this).children(".dropdownholder");
    if (!dh || dh.length==0) return; // don't add any drop down effects
    var anav = $(this).children("a.navitem");
    anav.addClass("dropdown-hdr");
    dh.css("display", "block");
  });

  $(".nav-level-1").mouseout(function() {
    var dh = $(this).children(".dropdownholder");
    if (!dh || dh.length==0) return; // don't add any drop down effects

    var anav = $(this).children("a.navitem");
    anav.removeClass("dropdown-hdr");

    dh.css("display", "none");
  });

  $("#contactus").mouseover(function() {
    $("#dropdown").css("display", "block");
  });
  $("#contactus").mouseout(function() {
    $("#dropdown").css("display", "none");
  });
  /*$("a.undeco div").css("opacity", "1");

   $("a.undeco div").mouseover(function() {
   $(this).css("opacity", "1");
   });

   $("a.undeco div").mouseout(function() {
   $(this).css("opacity", "1");
   });

   $("a.navitem").click(function() {
   $("a").removeClass("navitem2"); // find all links with this red linked class & remove them
   $(this).addClass("navitem2");
   Cufon.refresh();
   });
   */
  $('input#searchfieldId').resettable();
  $('input#first_name').resettable();
  $('input#last_name').resettable();
  $('input.clearfield').resettable();

  $("#dosearch").submit(function() {
    var searchInput = $("input:first").val();
    if (! searchInput) {
      return false;

    }
    return true;

  });


  $.featureList(
    $("#tabs li"),
    $("#output li"), undefined, undefined,
  {
    start_item  :  0,
    pause_on_hover: true,
    pause_on_output_hover: true,
    transition_interval: 40000
  }
    );

  $.featureList(
    $("#testimonials testi-nav"),
    $("#testimonials > ul > li"),
    $("#testi-nav a.lnavsmall"),
    $("#testi-nav a.rnavsmall"),
  {
    start_item  :  0,
    pause_on_hover: true,
    use_slidedown: true,
    pause_on_output_hover: true,
    transition_interval: 13000
  }
    );

  validateForm("#register");
  var highslide_forms = $('form.highslide-html-form');
  for (var i = 0; i < highslide_forms.length; i++) {

    validateForm("#" + highslide_forms[i].id)
  }

  visitorGeolocation = new GeoLocate(false, true, 'visitorGeolocation');
  var callback = function() {
  };
  visitorGeolocation.checkCookie(callback);

  registerQtip();

  registerChat();

  fixTableWidth();
});

function fixTableWidth() {
  var in2 = $("div.outGrey > div.inGrey2");
  in2.each(function(i) {
    var w = $(this).width();
    var i = $(this).innerWidth();
    var o = $(this).outerWidth();
    $(this).width(2 * w - o); // subtract border and padding from width to squish it inside top div's width
  });
}


var visitorGeolocation;

function registerChat() {
  $(".chat").click(function() {
    showChatWindow();
    return false;
  });

}

function registerQtip() {
  if ($.fn.qtip) {
    $.fn.qtip.styles.zmstyle = { // Last part is the name of the style
      fontSize: '12px',
      textAlign: 'center',
      padding: 3,
      border: {
        width: 1,
        radius: 5
      },
      tip: 'topLeft',
      /*  Doesn't work on IE
       position: {
       corner: {
       target: 'topMiddle',
       tooltip: 'bottomMiddle'
       }
       }, */
      name: 'cream' // Inherit the rest of the attributes from the preset dark style
    };
    $.fn.qtip.styles.centertip = { // Last part is the name of the style
      name: 'light', // Inherit the rest of the attributes from the preset dark style
      fontSize: '12px',
      textAlign: 'center',
      padding: 3,
      border: {
        width: 1,
        radius: 5
      },
      position: {
        corner: {
          target: 'bottomLeft',
          tooltip: 'topMiddle'
        }
      },
      tip: 'topMiddle' //position of tip triangular arrow mark
    };
  }

  if ($('.slideshow').length > 0)
    $('.slideshow').qtip({
      content: 'View slideshow of images',
      show: 'mouseover',
      hide: 'mouseout',
      style: 'zmstyle'
    });

  if ($('.hdvideo').length > 0) {
    $('.hdvideo').qtip({
      content: 'Watch HD video in 1280x720 with category playlists. Slower connection? No problem, use the YouTube link!',
      show: 'mouseover',
      hide: 'mouseout',
      style: 'zmstyle'
    });
  }

  /*
   hs.onActivate = function() {

   $('div.radio-img img[alt]').qtip({
   content: {
   text: false // Use each elements title attribute
   },
   style: 'centertip'
   });
   }
   */
}

function validateForm(formid) {
  var regform = $(formid);
  if (regform && regform.length > 0) {
    regform.validationEngine(
    {
      ajaxSubmit: true,
      ajaxSubmitFile: $(formid).attr("action")
    }
      );
  }

  if (formid == "#Feedback_form")
    return;
  /* Assume id of all forms is register and 1st a tag is submit button */
  $(formid + " a").click(function() {
    $(this).addClass(formid.substr(1) + "_currAnchor");
    $(formid).submit();  //do a normal form submit, will be intercepted by validator and ajax'd
    return false;
  });
}

var olarkApi;
function showChatWindow() {
  var lastOlarkState = $.cookie("olark_init");//, JSON.stringify(answer), { expires: 30 });
  if (lastOlarkState != "init") {
    $.cookie("olark_init", "init", { expires: 0.0104 });
  } else
  {
    /*alert("olark not init");*/
  }
  habla_window.show();
}
function hideChatWindow() {
  if (olarkApi)
    habla_window.hide();
}

function feedbackSubmit() {
  var caller = $('#Feedback_form')[0];
  var hsExpander;
  var clz = caller.className.split(' ');
  for (var i = 0; i < clz.length; i++) {
    var c = clz[i];
    if (c == "highslide-html-form") {
      if (parent.window.hs) {
        var currHs = parent.window.hs;
        var anchorId = caller.id.replace(/_form$/, "");
        for (var key = 0; key < currHs.expanders.length; key++) {
          hsExpander = currHs.expanders[key];
          if (hsExpander && hsExpander.a.id == anchorId) {
            break;
          }
          hsExpander = null;
        }
      }
      break;
    }
  }
  if (hsExpander) {
    hsExpander.close();
  }
  var d = $($('#Feedback_form')[0]).serialize();
  $.ajax({ type: 'POST', url: '/jsp/feedback.jsp',data:d,
    success: function(msg) {
    }});
}

function startDownload(product, downloadId) {
  alert(product);
  alert(downloadId);
  alert("your download will begin shortly!");
}




