var myDateSel;
var myDateSel1;
var menuPositioned = 0;
var myDynTips;

var tipsCfg = {
            tipBlankImage: '/images/blank.gif',
            tipButtonClass: 'tipBtn',
            tipAttachTo: 'needtip',
            tipClassName: 'tipDiv', 
            tipFetchUrl: '/tips.php',
            tipShowTime: 10
            }

function setUpMenu(){
    if(menuPositioned == 1) return;
    var oMenu = $('nav');
    x = oMenu.getWidth();
    gg = Element.positionedOffset('page');
    tx = $('page').getWidth();
    pageRight = gg[0] + tx;
    oMenu.absolutize();
    oMenu.remove();
    $$('body')[0].appendChild(oMenu);
    oMenu.setStyle({left: (pageRight - x) + 'px', width: x + 'px',zIndex : 99});
    menuPositioned = 1;
}

if (window.sidebar)
    menuPositioned = true;

// function code from dynamic drive
function bookmarksite(){
   var url = self.location;
   var title = document.title;
   if (window.sidebar) // firefox
	window.sidebar.addPanel(title, url, "");
   else if(window.opera && window.print){ // opera
	var elem = document.createElement('a');
	elem.setAttribute('href',url);
	elem.setAttribute('title',title);
	elem.setAttribute('rel','sidebar');
	elem.click();
   } 
   else if(document.all)// ie
	window.external.AddFavorite(url, title);
}

function watchChars(evt){
	var cont = Event.element(evt).parentNode;
	if(cont.innerHTML.search(/(\d+) characters/) == -1) return;
	var str = Event.element(evt).value;
	var tmp = cont.innerHTML.match(/(\d+) characters\)/);
	var maxChars = tmp[1];
	var _eleId = Event.element(evt).getAttribute('id');
	
	if(!$(_eleId + '_dynCount')){
	    var p = '<div id="' + _eleId + '_dynCount" class="dynTextareaCount"></div>';
	    Element.insert(cont, {before:p});
	}
	dynCount = $(_eleId + '_dynCount');


	if(str.length > maxChars){
		Event.element(evt).value = str.substring(0, maxChars);
		Event.stop();
	}
	dynCount.innerHTML = "" + str.length + "/" + maxChars;
}

function pluckDynCount(evt){
	var _eleId = Event.element(evt).getAttribute('id');
	if($(_eleId + '_dynCount')){
	    e = $(_eleId + '_dynCount');
	    e.parentNode.removeChild(e);
	}	
}

function limitCharsWatcher(){
    $$('textarea.textareawidth').each(function(textEntry){
		cont = textEntry.parentNode
	     if(cont.innerHTML.search(/(\d+) characters/) > -1){
		  Element.observe(textEntry,'keyup', watchChars, true); 
		  Element.observe(textEntry,'blur', pluckDynCount); 
		}
	});
    $$('textarea.textareasize').each(function(textEntry){
		cont = textEntry.parentNode
	     if(cont.innerHTML.search(/(\d+) characters/) > -1){
		  Element.observe(textEntry,'keyup', watchChars, true); 
		  Element.observe(textEntry,'blur', pluckDynCount);
		}
	});
     $$('input.txtboxWidth').each(function(textEntry){
		cont = textEntry.parentNode
	     if(cont.innerHTML.search(/(\d+) characters/) > -1){
		  Element.observe(textEntry,'keyup', watchChars, true); 
		  Element.observe(textEntry,'blur', pluckDynCount);
		}
	});
}

function setUpMenuDelayed(){
    setTimeout('setUpMenu()', 50);
    if($('frmGrabber'))
	Element.observe('frmGrabber','submit',contactGrabberCall,true);		
    
    if($('userAge'))
	myDateSel = new gDatePicker('userAge');	
    $$('a.addfavs').each(function(addfav){
		Element.observe(addfav, 'click', bookmarksite);
	});
    limitCharsWatcher();
    myDynTips = new gTipster(tipsCfg);
    }
function setUpMenuDelayedAdded(){
   setTimeout('setUpMenu()', 50);
    
  if($('joinDateafter'))
	myDateSel1 = new gDatePicker('joinDateafter');
  if($('joinDatebefore'))
	myDateSel2 = new gDatePicker('joinDatebefore');

	if($('lastpostafter'))
	myDateSel3 = new gDatePicker('lastpostafter');
	if($('lastpostbefore'))
	myDateSel4 = new gDatePicker('lastpostbefore');


    $$('a.addfavs').each(function(addfav){
		Element.observe(addfav, 'click', bookmarksite);
	});
    limitCharsWatcher();
     }
Event.observe(window, 'load', setUpMenuDelayed); 
Event.observe(window, 'load', setUpMenuDelayedAdded); 
window.onresize = function() {
	if(Prototype.Browser.IE){
		menuPositioned = 2;
		setTimeout('setUpMenu()', 25);
	}
  };

function reviewResp(type, reviewid,userId){
    var myAjax = new Ajax.Request(
        "/review-rate.html",
        {
            method: "post",
            parameters: {reviewId:reviewid,type:type,userId:userId}
            }
       );
	
}     

function commentResp(type, ReplyId,userId){
    var myAjax = new Ajax.Request(
        "/comment-rate.html",
        {
            method: "post",
            parameters: {ReplyId:ReplyId,type:type,userId:userId}
            }
       );
}   

function iMnotifyShow(url, from){
  $('msgFrom').innerHTML = 'You have a new message from ' + from + '<br><a href="' + url + '">Click to view</a>';
  $('msgnotify').show();
  setTimeout("$('msgnotify').hide()", 10000);
}

function selChange(evt){
    myDateSel.selChange(evt);
    myDateSel1.selChange(evt);
}



gDatePicker = Class.create();

gDatePicker.prototype = {
    initialize: function(oDateTxt){
       this.inputElement = oDateTxt;
       $(this.inputElement).hide();
       tmp = new Date();
       this.dynId = tmp.getTime();
       var container = $(this.inputElement).parentNode;
       this.makeSelectors(container);
    },
    makeSelectors: function(attachto){
     var defVal = ['','',''];
     if($(this.inputElement).value != ''){
        defVal = $(this.inputElement).value.split('-');
     }
     var html = this.mkMonth(defVal[1]) + '-' + this.mkDay(defVal[2]) + '-' + this.mkYear(defVal[0]);
     attachto.innerHTML += html;
     this.selectors = ['Y_' + this.dynId, 'M_' + this.dynId, 'D_' + this.dynId];
     this.yearSel = $('Y_' + this.dynId);
     this.monthSel = $('M_' + this.dynId);
     this.daySel = $('D_' + this.dynId);

     Event.observe(this.yearSel,'change',this.selChange.bindAsEventListener(this));
     Event.observe(this.monthSel,'change',this.selChange.bindAsEventListener(this));
     Event.observe(this.daySel,'change',this.selChange.bindAsEventListener(this));
    },
    mkYear: function(defVal){
        tmp = new Date();
        var txt = '<select id="Y_' + this.dynId + '" class="dobYearSel">';
        var ymax = tmp.getFullYear();
        var ymin = ymax - 100;
        this.ymin = ymin;
        txt += '<option>Year</option>';
        for(var i = ymin; i <= ymax; i ++){
            txt += '<option ';
            if(parseInt(defVal) == i)
                txt += 'selected="selected"';
            txt += '>' + i + '</option>';
        }
        txt += '</select>';
        return txt;
    },
    mkMonth: function(defVal){
        var monthNames = ['January','February','March','April','May','June','July','August','September','October','November','December'];
        var txt = '<select id="M_' + this.dynId + '" class="dobMonthSel">';
        txt += '<option>Month</option>';
        for(var i = 0; i < 12; i ++){
            txt += '<option ';
            if(parseInt(defVal.gsub(/0(\d)/, '#{1}' )) == (i + 1))
                txt += 'selected="selected"';
            txt += '>' + monthNames[i] + '</option>';
        }
        txt += '</select>';
        return txt;
    },
    mkDay: function(defVal){
        var txt = '<select id="D_' + this.dynId + '" class="dobDaySel">';
        txt += '<option>Day</option>';
        for(var i = 1; i < 32; i ++){
            txt += '<option ';
            if(parseInt(defVal.gsub(/0(\d)/, '#{1}' )) == i)
                txt += 'selected="selected"';
            txt += '>' + i + '</option>';
        }
        txt += '</select>';
        return txt;
    },
    selChange: function(evt){
        var doproc = true;
        this.selectors.each(function(selector){
            if($(selector).selectedIndex == 0) doproc = false;
        });
        if(doproc == false){
             $(this.inputElement).value = '';
             return;
             }
        try{
            var validDate = new Date(($(this.selectors[0]).selectedIndex - 1) + this.ymin, 
                            $(this.selectors[1]).selectedIndex - 1, 
                            $(this.selectors[2]).selectedIndex);
            if(validDate.getMonth() !== $(this.selectors[1]).selectedIndex - 1){
                Event.element(evt).selectedIndex = 0;
                Element.addClassName(Event.element(evt),'selErr');
                setTimeout("$('" + Event.element(evt).id + "').removeClassName('selErr')", 1500);
                $(this.inputElement).value = "";
                return;
            }else 
                this.setDate(validDate);
        }catch(e){
            return;
        }
    },
    setDate: function(oJsDate){
        var y = oJsDate.getFullYear();
        var m = oJsDate.getMonth() + 1;
        var d = oJsDate.getDate();
        
        if(m < 10) m = '0' + m;
        if(d < 10) d = '0' + d;
        $(this.inputElement).value = "" + y + "-" + m + "-" + d;
        if($(this.inputElement + 'Debug'))
           $(this.inputElement + 'Debug').value = $(this.inputElement).value + ';' + oJsDate.toString();
    }
};


gTipster = Class.create();

gTipster.prototype = {
  initialize: function(config){
    this.attachTo = config.tipAttachTo ? config.tipAttachTo : 'needTip';
    this.blankImage = config.tipBlankImage ? config.tipBlankImage : 'blank.gif';
    this.buttonClass = config.tipButtonClass ? config.tipButtonClass : 'tipBtn';
    this.pClassName = config.tipClassName ? config.tipClassName : 'tipDiv';
    this.fetchUrl = config.tipFetchUrl ? config.tipFetchUrl : 'tips.php';
    this.showTime = config.tipShowTime ? config.tipShowTime : 10;
    
    this.idTag = Math.random().toString().substring(3,7);
    var myInstance = this;
    $$("." + this.attachTo).each(
        function (attachTo) { 
            var tId = myInstance.buttonClass + attachTo.getAttribute('id');
            var p = '<img src="' + myInstance.blankImage + '" id = "' + tId + '" class="' + myInstance.buttonClass + '" key="' + attachTo.getAttribute('id') + '" alt="Press to See Tip" title="Press to See Tip" width="19px" height="19px" />';
            if($(attachTo).getAttribute('id') != 'userAge')
                Element.insert(attachTo, {after: p});
            else 
                Element.insert($(attachTo).parentNode, {bottom: p});
	               
            $(tId).show();
           }
        );
      this.attachClick();
   },
  buttonClick: function(evt){
    var button = Event.element(evt);
    var key = button.getAttribute('key');
    if(this.timer && this.nextShow != this.pClassName + key){
        clearTimeout(this.timer);
        $(this.nextShow).hide();
    }
    this.nextShow = this.pClassName + key;
    if($(this.nextShow)){
       this.showTip();
    }else{    
        var p = '<p class="' + this.pClassName + '" id="' + this.nextShow + '" style="display:none"></p>';
        Element.insert(button.parentNode, {after: p});
        var options = { method: 'POST', parameters: 'tag=' + key + '&ref=' + document.location.href, onComplete: this.showTip.bindAsEventListener(this)};
        var fetchTip = new Ajax.Updater(
            this.nextShow, 
            this.fetchUrl,  
            options
            );
    }
  },
  showTip: function(evt){
        $(this.nextShow).show();
        this.timer = setTimeout("$('" + this.nextShow + "').hide()", this.showTime * 1000);
  },
  hoverButton: function(evt){
        Event.element(evt).addClassName('tipBtnHover');
  },
  rolloutBtn: function(evt){
        Event.element(evt).removeClassName('tipBtnHover');
  },
  attachClick: function(){
      var myInstance = this;
      $$("img." + this.buttonClass).each(function (iButton) {
           Element.observe(iButton, 'click', myInstance.buttonClick.bindAsEventListener(myInstance));
           if(Prototype.Browser.IE){
              Element.observe(iButton, 'mouseover', myInstance.hoverButton.bindAsEventListener(myInstance));
              Element.observe(iButton, 'mouseout', myInstance.rolloutBtn.bindAsEventListener(myInstance));
           }
        });    
  }
};




