// JavaScript Document

//==================================================================================
//Javascript include
//====================================================================================


//==================================================================================
//Text for form errors
//====================================================================================

formcheckLanguage = {
	required: "Hang on, I know you are in a rush to submit your issue but please fill me up :-)",
	alpha: "This field accepts alphabetic characters only.",
	alphanum: "I only accept numbers and letters only.",
	nodigit: "No digits are accepted.",
	digit: "Hey, I know some math...please fill me with numbers",
	digitmin: "The number must be at least %0",
	digitltd: "The value must be between %0 and %1",
	number: "Please enter a valid number.",
	email: "Please enter a valid email: <br /><span>E.g. yourname@domain.com</span>",
	phone: "Please enter a valid phone.",
	url: "Please enter a valid url: <br /><span>E.g. http://www.domain.com</span>",
	
	confirm: "This field is different from %0",
	differs: "This value must be different of %0",
	length_str: "The length is incorrect, it must be between %0 and %1",
	length_fix: "The length is incorrect, it must be exactly %0 characters",
	lengthmax: "The length is incorrect, it must be at max %0",
	lengthmin: "Hey, sorry for being such a pain in the neck but for your title to make sense the characters have to be more than %0",
	checkbox: "Please check the box",
	radios: "Please select a radio",
	select: "Please choose a value"
};

//==========================================================
// Background Color Change
//==========================================================
var YOOTools = {
		
	start: function() {
		

		/* Background fx */
		var bgColors = false;
		var duration = 9000;

		switch (YtSettings.pulse) {
			case 'color':
				duration = 5000;
				switch (YtSettings.itemColor) {
					case 'red':
						bgColors = ['#C8001E', '#6E000F'];
				  		break;
					case 'blue':
						bgColors = ['#006975', '#005A6E'];
				  		break;
					case 'pink':
						bgColors = ['#C800C8', '#640064'];
				  		break;
					case 'orange':
						bgColors = ['#DC5000', '#6E2800'];
				  		break;
					case 'green':
						bgColors = ['#78C800', '#3C6400'];
				  		break;
					case 'yellow':
						bgColors = ['#FFC800', '#6E5500'];
				  		break;
					case 'lilac':
						bgColors = ['#6432C8', '#371E6E'];
				  		break;
					case 'turquoise':
						bgColors = ['#00DCB4', '#006E5A'];
				  		break;
				}
		  		break;
			case 'rainbow':
				duration = 9000;
				bgColors = ['#C8001E', '#DC5000', '#FFC800', '#78C800', '#00DCB4', '#00BED2', '#6432C8', '#C800C8'];
		  		break;
		}

		if (bgColors) {
			new YOOBackgroundFx({ 'colors': bgColors, 'duration': duration });
		}
		


	}

	

};

/* Add functions on window load */
window.addEvent('domready', YOOTools.start);

/* Load IE6 fix */
if (window.ie6) {
	YOOTools.include('addons/ie6fix.js');
	YOOTools.include('yoo_ie6fix.js');
}

var YtSettings = { tplurl: '', color: 'default', itemColor: 'blue', pulse: 'color', layout: 'left', fontDefault: 'font-medium', widthDefault: 'width-thin', widthThinPx: 720, widthWidePx: 960, widthFluidPx: 0.9 };

//===========================================================
// Sliding effect for adding post and comments
//===========================================================
var timerlen = 5;
var slideAniLen = 250;

var timerID = new Array();
var startTime = new Array();
var obj = new Array();
var endHeight = new Array();
var moving = new Array();
var dir = new Array();

function slidedown(objname){
        if(moving[objname])
                return;

        if(document.getElementById(objname).style.display != "none")
                return; // cannot slide down something that is already visible

        moving[objname] = true;
        dir[objname] = "down";
        startslide(objname);
}

function slideup(objname){
        if(moving[objname])
                return;

        if(document.getElementById(objname).style.display == "none")
                return; // cannot slide up something that is already hidden

        moving[objname] = true;
        dir[objname] = "up";
        startslide(objname);
}

function startslide(objname){
        obj[objname] = document.getElementById(objname);

        endHeight[objname] = parseInt(obj[objname].style.height);
        startTime[objname] = (new Date()).getTime();

        if(dir[objname] == "down"){
                obj[objname].style.height = "1px";
        }

        obj[objname].style.display = "block";

        timerID[objname] = setInterval('slidetick(\'' + objname + '\');',timerlen);
}

function slidetick(objname){
        var elapsed = (new Date()).getTime() - startTime[objname];

        if (elapsed > slideAniLen)
                endSlide(objname)
        else {
                var d =Math.round(elapsed / slideAniLen * endHeight[objname]);
                if(dir[objname] == "up")
                        d = endHeight[objname] - d;

                obj[objname].style.height = d + "px";
        }

        return;
}

function endSlide(objname){
        clearInterval(timerID[objname]);

        if(dir[objname] == "up")
                obj[objname].style.display = "none";

        obj[objname].style.height = endHeight[objname] + "px";

        delete(moving[objname]);
        delete(timerID[objname]);
        delete(startTime[objname]);
        delete(endHeight[objname]);
        delete(obj[objname]);
        delete(dir[objname]);

        return;
}


//===================================================
//Tooltip
//===================================================


// Here's one illustrating a decimal tipStick value so it floats along behind the cursor.
var editTip = new TipObj('editTip');
with (editTip)
{
 template = '<table bgcolor="#000000" cellpadding="1" cellspacing="0" width="20" border="0">' +
  '<tr><td><table bgcolor="#339966" cellpadding="4" cellspacing="0" width="100%" border="0">' +
  '<tr><td align="center" class="tipClass">%3%</td></tr></table></td></tr></table>';

 tips.floating = new Array(5, 5, 100, 'Edit');

 tipStick = 0.2;
}

var delTip = new TipObj('delTip');
with (delTip)
{
 template = '<table bgcolor="#000000" cellpadding="1" cellspacing="0" width="20" border="0">' +
  '<tr><td><table bgcolor="#339966" cellpadding="4" cellspacing="0" width="100%" border="0">' +
  '<tr><td align="center" class="tipClass">%3%</td></tr></table></td></tr></table>';

 tips.floating = new Array(5, 5, 100, 'Delete');

 tipStick = 0.2;
}
/******************************************/
/* Message Box*/
/******************************************/

DHTML_modalMessage = function()
{
	var url;								// url of modal message
	var htmlOfModalMessage;					// html of modal message
	
	var divs_transparentDiv;				// Transparent div covering page content
	var divs_content;						// Modal message div.
	var iframe;								// Iframe used in ie
	var layoutCss;							// Name of css file;
	var width;								// Width of message box
	var height;								// Height of message box
	
	var existingBodyOverFlowStyle;			// Existing body overflow css
	var dynContentObj;						// Reference to dynamic content object
	var cssClassOfMessageBox;				// Alternative css class of message box - in case you want a different appearance on one of them
	var shadowDivVisible;					// Shadow div visible ? 
	var shadowOffset; 						// X and Y offset of shadow(pixels from content box)
	var MSIE;
		
	this.url = '';							// Default url is blank
	this.htmlOfModalMessage = '';			// Default message is blank
	this.layoutCss = 'modal-message.css';	// Default CSS file
	this.height = 200;						// Default height of modal message
	this.width = 400;						// Default width of modal message
	this.cssClassOfMessageBox = false;		// Default alternative css class for the message box
	this.shadowDivVisible = true;			// Shadow div is visible by default
	this.shadowOffset = 5;					// Default shadow offset.
	this.MSIE = false;
	if(navigator.userAgent.indexOf('MSIE')>=0) this.MSIE = true;
	

}

DHTML_modalMessage.prototype = {
	// {{{ setSource(urlOfSource)
    /**
     *	Set source of the modal dialog box
     * 	
     *
     * @public	
     */		
	setSource : function(urlOfSource)
	{
		this.url = urlOfSource;
		
	}	
	// }}}	
	,
	// {{{ setHtmlContent(newHtmlContent)
    /**
     *	Setting static HTML content for the modal dialog box.
     * 	
     *	@param String newHtmlContent = Static HTML content of box
     *
     * @public	
     */		
	setHtmlContent : function(newHtmlContent)
	{
		this.htmlOfModalMessage = newHtmlContent;
		
	}
	// }}}		
	,
	// {{{ setSize(width,height)
    /**
     *	Set the size of the modal dialog box
     * 	
     *	@param int width = width of box
     *	@param int height = height of box
     *
     * @public	
     */		
	setSize : function(width,height)
	{
		if(width)this.width = width;
		if(height)this.height = height;		
	}
	// }}}		
	,		
	// {{{ setCssClassMessageBox(newCssClass)
    /**
     *	Assign the message box to a new css class.(in case you wants a different appearance on one of them)
     * 	
     *	@param String newCssClass = Name of new css class (Pass false if you want to change back to default)
     *
     * @public	
     */		
	setCssClassMessageBox : function(newCssClass)
	{
		this.cssClassOfMessageBox = newCssClass;
		if(this.divs_content){
			if(this.cssClassOfMessageBox)
				this.divs_content.className=this.cssClassOfMessageBox;
			else
				this.divs_content.className='modalDialog_contentDiv';	
		}
					
	}
	// }}}		
	,	
	// {{{ setShadowOffset(newShadowOffset)
    /**
     *	Specify the size of shadow
     * 	
     *	@param Int newShadowOffset = Offset of shadow div(in pixels from message box - x and y)
     *
     * @public	
     */		
	setShadowOffset : function(newShadowOffset)
	{
		this.shadowOffset = newShadowOffset
					
	}
	// }}}		
	,	
	// {{{ display()
    /**
     *	Display the modal dialog box
     * 	
     *
     * @public	
     */		
	display : function()
	{
		if(!this.divs_transparentDiv){
			this.__createDivs();
		}	
		
		// Redisplaying divs
		this.divs_transparentDiv.style.display='block';
		this.divs_content.style.display='block';
		this.divs_shadow.style.display='block';		
		if(this.MSIE)this.iframe.style.display='block';	
		this.__resizeDivs();
		
		/* Call the __resizeDivs method twice in case the css file has changed. The first execution of this method may not catch these changes */
		window.refToThisModalBoxObj = this;		
		setTimeout('window.refToThisModalBoxObj.__resizeDivs()',150);
		
		this.__insertContent();	// Calling method which inserts content into the message div.
	}
	// }}}		
	,
	// {{{ ()
    /**
     *	Display the modal dialog box
     * 	
     *
     * @public	
     */		
	setShadowDivVisible : function(visible)
	{
		this.shadowDivVisible = visible;
	}
	// }}}	
	,
	// {{{ close()
    /**
     *	Close the modal dialog box
     * 	
     *
     * @public	
     */		
	close : function()
	{
		//document.documentElement.style.overflow = '';	// Setting the CSS overflow attribute of the <html> tag back to default.
		
		/* Hiding divs */
		this.divs_transparentDiv.style.display='none';
		this.divs_content.style.display='none';
		this.divs_shadow.style.display='none';
		if(this.MSIE)this.iframe.style.display='none';
		
	}	
	// }}}	
	,
	// {{{ __addEvent()
    /**
     *	Add event
     * 	
     *
     * @private	
     */		
	addEvent : function(whichObject,eventType,functionName,suffix)
	{ 
	  if(!suffix)suffix = '';
	  if(whichObject.attachEvent){ 
	    whichObject['e'+eventType+functionName+suffix] = functionName; 
	    whichObject[eventType+functionName+suffix] = function(){whichObject['e'+eventType+functionName+suffix]( window.event );} 
	    whichObject.attachEvent( 'on'+eventType, whichObject[eventType+functionName+suffix] ); 
	  } else 
	    whichObject.addEventListener(eventType,functionName,false); 	    
	} 
	// }}}	
	,
	// {{{ __createDivs()
    /**
     *	Create the divs for the modal dialog box
     * 	
     *
     * @private	
     */		
	__createDivs : function()
	{
		// Creating transparent div
		this.divs_transparentDiv = document.createElement('DIV');
		this.divs_transparentDiv.className='modalDialog_transparentDivs';
		this.divs_transparentDiv.style.left = '0px';
		this.divs_transparentDiv.style.top = '0px';
		
		document.body.appendChild(this.divs_transparentDiv);
		// Creating content div
		this.divs_content = document.createElement('DIV');
		this.divs_content.className = 'modalDialog_contentDiv';
		this.divs_content.id = 'DHTMLSuite_modalBox_contentDiv';
		this.divs_content.style.zIndex = 100000;
		
		if(this.MSIE){
			this.iframe = document.createElement('<IFRAME src="about:blank" frameborder=0>');
			this.iframe.style.zIndex = 90000;
			this.iframe.style.position = 'absolute';
			document.body.appendChild(this.iframe);	
		}
			
		document.body.appendChild(this.divs_content);
		// Creating shadow div
		this.divs_shadow = document.createElement('DIV');
		this.divs_shadow.className = 'modalDialog_contentDiv_shadow';
		this.divs_shadow.style.zIndex = 95000;
		document.body.appendChild(this.divs_shadow);
		window.refToModMessage = this;
		this.addEvent(window,'scroll',function(e){ window.refToModMessage.__repositionTransparentDiv() });
		this.addEvent(window,'resize',function(e){ window.refToModMessage.__repositionTransparentDiv() });
		

	}
	// }}}
	,
	// {{{ __getBrowserSize()
    /**
     *	Get browser size
     * 	
     *
     * @private	
     */		
	__getBrowserSize : function()
	{
    	var bodyWidth = document.documentElement.clientWidth;
    	var bodyHeight = document.documentElement.clientHeight;
    	
		var bodyWidth, bodyHeight; 
		if (self.innerHeight){ // all except Explorer 
		 
		   bodyWidth = self.innerWidth; 
		   bodyHeight = self.innerHeight; 
		}  else if (document.documentElement && document.documentElement.clientHeight) {
		   // Explorer 6 Strict Mode 		 
		   bodyWidth = document.documentElement.clientWidth; 
		   bodyHeight = document.documentElement.clientHeight; 
		} else if (document.body) {// other Explorers 		 
		   bodyWidth = document.body.clientWidth; 
		   bodyHeight = document.body.clientHeight; 
		} 
		return [bodyWidth,bodyHeight];		
		
	}
	// }}}	
	,
	// {{{ __resizeDivs()
    /**
     *	Resize the message divs
     * 	
     *
     * @private	
     */	
    __resizeDivs : function()
    {
    	
    	var topOffset = Math.max(document.body.scrollTop,document.documentElement.scrollTop);

		if(this.cssClassOfMessageBox)
			this.divs_content.className=this.cssClassOfMessageBox;
		else
			this.divs_content.className='modalDialog_contentDiv';	
			    	
    	if(!this.divs_transparentDiv)return;
    	
    	// Preserve scroll position
    	var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
    	var sl = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);
    	
    	window.scrollTo(sl,st);
    	setTimeout('window.scrollTo(' + sl + ',' + st + ');',10);

    	this.__repositionTransparentDiv();
    	

		var brSize = this.__getBrowserSize();
		var bodyWidth = brSize[0];
		var bodyHeight = brSize[1];
    	
    	// Setting width and height of content div
      	this.divs_content.style.width = this.width + 'px';
    	this.divs_content.style.height= this.height + 'px';  	
    	
    	// Creating temporary width variables since the actual width of the content div could be larger than this.width and this.height(i.e. padding and border)
    	var tmpWidth = this.divs_content.offsetWidth;	
    	var tmpHeight = this.divs_content.offsetHeight;
    	
    	
    	// Setting width and height of left transparent div
    	
    	

    	
    	
		
    	this.divs_content.style.left = Math.ceil((bodyWidth - tmpWidth) / 2) + 'px';;
    	this.divs_content.style.top = (Math.ceil((bodyHeight - tmpHeight) / 2) +  topOffset) + 'px';
    	
 		if(this.MSIE){
 			this.iframe.style.left = this.divs_content.style.left;
 			this.iframe.style.top = this.divs_content.style.top;
 			this.iframe.style.width = this.divs_content.style.width;
 			this.iframe.style.height = this.divs_content.style.height;
 		}
 		
    	this.divs_shadow.style.left = (this.divs_content.style.left.replace('px','')/1 + this.shadowOffset) + 'px';
    	this.divs_shadow.style.top = (this.divs_content.style.top.replace('px','')/1 + this.shadowOffset) + 'px';
    	this.divs_shadow.style.height = tmpHeight + 'px';
    	this.divs_shadow.style.width = tmpWidth + 'px';
    	
    	
    	
    	if(!this.shadowDivVisible)this.divs_shadow.style.display='none';	// Hiding shadow if it has been disabled
    	
    	
    }
    // }}}	
    ,
	// {{{ __insertContent()
    /**
     *	Insert content into the content div
     * 	
     *
     * @private	
     */	    
    __repositionTransparentDiv : function()
    {
    	this.divs_transparentDiv.style.top = Math.max(document.body.scrollTop,document.documentElement.scrollTop) + 'px';
    	this.divs_transparentDiv.style.left = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft) + 'px';
		var brSize = this.__getBrowserSize();
		var bodyWidth = brSize[0];
		var bodyHeight = brSize[1];
    	this.divs_transparentDiv.style.width = bodyWidth + 'px';
    	this.divs_transparentDiv.style.height = bodyHeight + 'px';		
		   	
    }
	// }}}	
	,
	// {{{ __insertContent()
    /**
     *	Insert content into the content div
     * 	
     *
     * @private	
     */	
    __insertContent : function()
    {
		if(this.url){	// url specified - load content dynamically
			ajax_loadContent('DHTMLSuite_modalBox_contentDiv',this.url);
		}else{	// no url set, put static content inside the message box
			this.divs_content.innerHTML = this.htmlOfModalMessage;	
		}
    }		
}


messageObj = new DHTML_modalMessage();	// We only create one object of this class
messageObj.setShadowOffset(5);	// Large shadow


function displayMessage(url)
{
	
	messageObj.setSource(url);
	messageObj.setCssClassMessageBox(false);
	messageObj.setSize(400,200);
	messageObj.setShadowDivVisible(true);	// Enable shadow for these boxes
	messageObj.display();
}

function displayStaticMessage(messageContent,cssClass)
{
	messageObj.setHtmlContent(messageContent);
	messageObj.setSize(300,150);
	messageObj.setCssClassMessageBox(cssClass);
	messageObj.setSource(false);	// no html source since we want to use a static message here.
	messageObj.setShadowDivVisible(false);	// Disable shadow for these boxes	
	messageObj.display();
	
	
}

function closeMessage()
{
	messageObj.close();	
}


//==================================================================================
//Javascript include
//====================================================================================
function Confirmdelete(){
   var AlertBox = "";
   
   AlertBox=confirm("Are you sure you want to delete this post?");
   
   return AlertBox;
}
/**************************************************************
load pages via AJAX.
**************************************************************/

var pageLoader = new Class({
							  
	getOptions: function(){
		return {
			links: '.loadMe',
			loadInTo: 'content',
			loadFrom: 'content',
			onStart: Class.empty,
			onComplete: Class.empty
		};
	},

	initialize: function(options){
	
		this.setOptions(this.getOptions(), options);
		
		this.links = $$(this.options.links);
		this.links.each(function(el,i){
			el.addEvent('click',function(e){
				if(e != undefined){
					new Event(e).stop();
				}
				this.start(el);
			}.bind(this));
		}.bind(this));
	},
	
	setContent: function(){
		var temp = new Element('div').setProperties({id:'temp'}).setStyles({display:'none'}).injectInside(document.body);
		temp.setHTML(this.content.response.text);
		var newEl = $('temp').getElement('#'+this.options.loadFrom);
		$(this.options.loadInTo).replaceWith(newEl);
		newEl.setProperties({id:this.options.loadInTo});
		temp.remove();
	},
	
	start: function(el){
		//this.options.onStart();
		this.content = new Ajax(el.href, {
								method: 'get',
								onComplete: this.complete.bind(this),
								autoCancel: true
							}).request();
	},
	
	complete: function(){
		this.setContent();
		//this.options.onComplete();
	}

});
pageLoader.implement(new Events);
pageLoader.implement(new Options);


/*************************************************************/



jQuery.noConflict();
/*jQuery().ready(function() {
									
		jQuery(".rss_notice").jnotice({
									autoClose: 5000,
									openNow: true,
									position: "top", 
									animation:"slide",
									animationSpeed: 400});
									
		
	});*/
jQuery(document).ready(function() {
	
	// Expand Panel
	jQuery("#open").click(function(){
		jQuery("div#panel").slideDown("slow");
	
	});	
	
	// Collapse Panel
	jQuery("#close").click(function(){
		jQuery("div#panel").slideUp("slow");	
	});		
	
	// Switch buttons from "Log In | Register" to "Close Panel" on click
	jQuery("#toggle a").click(function () {
		jQuery("#toggle a").toggle();
	});		
	/*===========================================================*/
	// Checkboxes
	/*===========================================================*/
			jQuery(".checklist .checkbox-select").click(
				function(event) {
					event.preventDefault();
					jQuery(this).parent().addClass("selected");
					jQuery(this).parent().find(":checkbox").attr("checked","checked");
					
				}
			);
			
			jQuery(".checklist .checkbox-deselect").click(
				function(event) {
					event.preventDefault();
					jQuery(this).parent().removeClass("selected");
					jQuery(this).parent().find(":checkbox").removeAttr("checked");
					
				}
			);
			
		jQuery("input[@type=checkbox][checked]").each(
				function(){
					jQuery(this).parent().addClass("selected");
					jQuery(this).parent().find(":checkbox").attr("checked","checked");
				}
		);					 
					
});


/******************************************/
/* when the dom is ready */
/******************************************/

window.addEvent('domready', function() {
									 
					box = new MultiBox('mb', {descClassName: 'multiBoxDesc', useOverlay: true});
								 
						 
	/*===========================================================*/
	// Deleting Records
	/*===========================================================*/

	$$('a.delete').each(function(el) {
		el.addEvent('click',function(e) {
			e.stop();
			var parent = el.getParent('div');
			var request = new Request({
				url: 'index.php',
				link: 'chain',
				method: 'get',
				data: {
					'delete': parent.get('id').replace('record-',''),
					ajax: 1
				},
				onRequest: function() {
					new Fx.Tween(parent,{
						duration:300
					}).start('background-color', '#fb6c6c');
				},
				onSuccess: function() {
					new Fx.Slide(parent,{
						duration:300,
						onComplete: function() {
							parent.dispose();
						}
					}).slideOut();
				}
			}).send();
		});
	});

									 
									 
	/*===========================================================*/
	// AUTOCOMPLETE 
	/*===========================================================*/
/**
	 * Simple example, backend returns a list of <li> elements,
	 * processed by Autocompleter.Request.HTML.
	 */
 
	var inputWord2 = $('tags'); 
	new Autocompleter.Request.JSON(inputWord2, 'tags.php', {
		'indicatorClass': 'autocompleter-loading', // class added to the input during request
		'postVar': 'tags',
		'multiple': true,
		'selectFirst': true,
		'selectMode': false,
		'minLength': 1
	});


 
									 
									 
									 
									 
									 
									 
	/*===========================================================*/
	// WYSIWYG 
	/*===========================================================*/


	window.addEvent('load', function(){
				$('issue1').mooEditable({
					actions: 'bold italic underline strikethrough | insertunorderedlist insertorderedlist indent outdent | undo redo | createlink unlink | urlimage | toggleview'
				});

			});
	//============================================
	// form validation
	//============================================
	
	new FormCheck('gotissuez');	
	new FormCheck('bids');	
	//----------------------------------------------------------------------	
	//For effects on the links	
	//======================================================================
	
	$each($$('a'), function(el) {
		var original = el.getStyle('color');
		var morph = new Fx.Morph(el,{ 'duration':'300', link:'cancel' });
		el.addEvents({
			'mouseenter' : function() { morph.start({ 'color':'#0066CC' }) },
			'mouseleave' : function() { morph.start({ 'color': original }) }
		});
	});
	
	
		//------------------------------------------------------------
		
		//show the post buttons: me too, I can fix this and non issue
		
		//-------------------------------------------------------------
		
		$$('a.button').each(function(el) {
		var img = el.getElement('img'), running = false;
		var fx2 = new Fx.Morph(img, {duration: 100, link: 'chain', onChainComplete:function() { running = false; } });
		var fx1 = new Fx.Morph(img, {duration: 200, link: 'chain', onComplete:function() {
				fx2.start({'top':'-27px'}).start({'top':'-24px'}).start({'top':'-26px'}).start({'top':'-24px'});
			}
		});
		//on mouse overr
		el.addEvent('mouseenter',function() {
			if(!running) {
				fx1.start({'top':'-30px'}).start({'top':'-24px'});
				running = true;
			}
		});
	  });



});