// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

onerror = handleErrors;

function handleErrors(e,u,l){
	var x="There was an error on this page.\n\n";
	x+="An internal programming error may keep\n";
	x+="this page from displaying properly.\n";
	x+="Click OK to continue.\n\n";
	x+="Error message: " + e + "\n";
	x+="URL: " + u + "\n";
	x+="Line: " + l;

	//var _errorImg=new Image;
	//_errorImg.src='/error/bug_report?subject=JavaScript%20Error&body=JavaScript%20error%20trapped';

  if(self.location.href.indexOf('hidejserrors=false') != -1) return false;
  if((self.location.href.indexOf('hidejserrors=true') >= 0) || (self.location.hostname.indexOf('foopets.com')!=-1)) return true;
};



// Start browser detect ( http://www.quirksmode.org/js/detect.html )
var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
            || this.searchVersion(navigator.appVersion)
            || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++)	{
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
        {
            string: navigator.userAgent,
            subString: "Chrome",
            identity: "Chrome"
        },
        { 	string: navigator.userAgent,
            subString: "OmniWeb",
            versionSearch: "OmniWeb/",
            identity: "OmniWeb"
        },
        {
            string: navigator.vendor,
            subString: "Apple",
            identity: "Safari",
            versionSearch: "Version"
        },
        {
            prop: window.opera,
            identity: "Opera"
        },
        {
            string: navigator.vendor,
            subString: "iCab",
            identity: "iCab"
        },
        {
            string: navigator.vendor,
            subString: "KDE",
            identity: "Konqueror"
        },
        {
            string: navigator.userAgent,
            subString: "Firefox",
            identity: "Firefox"
        },
        {
            string: navigator.vendor,
            subString: "Camino",
            identity: "Camino"
        },
        {		// for newer Netscapes (6+)
            string: navigator.userAgent,
            subString: "Netscape",
            identity: "Netscape"
        },
        {
            string: navigator.userAgent,
            subString: "MSIE",
            identity: "Explorer",
            versionSearch: "MSIE"
        },
        {
            string: navigator.userAgent,
            subString: "Gecko",
            identity: "Mozilla",
            versionSearch: "rv"
        },
        { 		// for older Netscapes (4-)
            string: navigator.userAgent,
            subString: "Mozilla",
            identity: "Netscape",
            versionSearch: "Mozilla"
        }
    ],
    dataOS : [
        {
            string: navigator.platform,
            subString: "Win",
            identity: "Windows"
        },
        {
            string: navigator.platform,
            subString: "Mac",
            identity: "Mac"
        },
        {
            string: navigator.platform,
            subString: "Linux",
            identity: "Linux"
        }
    ]

};
BrowserDetect.init();
// End browser detect

function number_with_delimiter(val) {
  var val = String(val);
  var regEx = /(\d+)(\d{3})/;
  while (regEx.test(val)) {
      val = val.replace(regEx, '$1' + ',' + '$2');
  }
  return val;
}

function setCookie(c_name,value,expiredays){
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+
    ";path=/";
};

function getCookie(c_name){
  if(document.cookie.length>0){
    c_start=document.cookie.indexOf(c_name + "=");
    if(c_start!=-1){
      c_start=c_start + c_name.length+1;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
      return unescape(document.cookie.substring(c_start,c_end));
    }
  }
  return "";
};

var updater;

function stopAds(){
  updater.stop();
};

function runAds(intervalSeconds,stopAfterMinutes){
  if ($('ad')){
    // rotate ad banner every 30 seconds
    updater = new Ajax.PeriodicalUpdater('ad', '/ad', {
      method: 'get',
      frequency: intervalSeconds,
      decay: 1,
      onSuccess: function (result){
        //TODO: ping google analytics with which ad ran
        //using an identifier in result.responseText
      }
      });
    // stop ad rotations after 3 minutes
    var temp = setTimeout(stopAds,(stopAfterMinutes * 60 * 1000));
  }
};

var myGambitAdUrl = false; // this gets set in application layout
function runGambitAds(interval,stopAfterViews){
  if ($('gambitAdIframe')){
    if (myGambitAdUrl && stopAfterViews > 0){
      $('gambitAdIframe').src = myGambitAdUrl;
      stopAfterViews = stopAfterViews - 1;
      //var temp = setTimeout("runGambitAds(" + interval + "," + stopAfterViews + ")",interval);
    }
  }
};

function openCurrencyCopy()
{
    new Ajax.Request('/misc/currency_copy?popup=true', {
        method: 'get',
        onSuccess: function(transport) {
           $('currency_copy').innerHTML=transport.responseText;
           Modalbox.show($('currency_copy'), {title: 'Information', width: 650, height: 415});
        }
    });
};

function attachTooltips(){
  $$('.tooltip').each(function(element) {
    if (element.rel && element.rel.length > 0){
        new Tip(element, element.rel);
    }
  });
};

// Setup "More Stuff" menu
function showMoreMenu(){
  $('more_dropdown').show();
  $('more_dropdown').setStyle({'zIndex':49999});

  // Keep "More" icon depressed
  $$('li#more_stuff a')[0].setStyle({'backgroundPosition':'-639px -36px'});
};

function hideMoreMenu(){
  $('more_dropdown').hide();

  // Deactivate "More" icon
  $$('li#more_stuff a')[0].setStyle({'backgroundPosition':'-639px 0'});
};

function appLoad(){
  attachTooltips();
};

function parseBuyProductResponse(data){
  if(data.errors){
    return data.errors;
  }
  else if(data.quantity){
    return data.quantity;
  }
  else{
    return 'Error 6770: No response';
  }
};

Number.prototype.toMinutesAndSeconds = function() {
	var nbr = Math.floor(this / 60);
	return (nbr+":")+(((nbr=(this-(nbr*60)))<10)?"0"+nbr:nbr);
}

function countdown_display(seconds, el_clock, el_warn, el_expire, warn_at, warn_msg, expired_msg) {
	el_clock.update((--seconds).toMinutesAndSeconds());
	if(seconds > 0) {
		window.setTimeout(function(){countdown_display(seconds, el_clock, el_warn, el_expire, warn_at, warn_msg, expired_msg)}, 1000);
	}
	if(warn_at && (seconds <= warn_at)) {
		el_warn.update(warn_msg);
    el_clock.setStyle({'backgroundColor':'#d14944'});
	}

	if (el_expire && expired_msg && (seconds == 0)) {
		el_expire.update(expired_msg);
	}
}



document.observe("dom:loaded", function(){
  appLoad();
});

