function check_for_unread_messages(){
	var unread = $('#unread_messages');
    if(USER_ID !== 1){
        $.getJSON('/messages/unread/'+USER_ID+'/'+unread.attr('title'), null, function(data){
            var unread = $('#unread_messages');
            if(parseFloat(data.unread) > 0)
            {
                var overlay = $('#new_messages_overlay');
                overlay.css('top', '-146px'); //unread.position().top + unread.outerHeight() - 5);
                overlay.css('left', '720px') //unread.position().left - overlay.outerWidth() + 20);
                overlay.fadeIn(1500);
                unread.attr('title', parseFloat(unread.attr('title')) + parseFloat(data.unread));
                unread.html(unread.attr('title') + ' unread');
            }
            else{
                unread.attr('title', parseFloat(unread.attr('title')) + parseFloat(data.unread));
                unread.html(unread.attr('title') + ' ' + UNREAD);
            }
        });
        setTimeout('check_for_unread_messages()', 60000);
    }
}

$(document).ready(function(){
	setTimeout('check_for_unread_messages()', 60000);
	$('#new_messages_overlay').click(function(){
		$(this).fadeOut(500);
		setTimeout("$(this).css('top', -1000);$(this).css('left', -1000);", 500);
	});
})

jQuery.mailchimp = {};
jQuery.mailchimp.service_uri = '/exchange/mailchimp_groups/';
jQuery.mailchimp.menuDefault = [ 
	{
		'Assign Email Groups': {
			onclick: function(menuItem,menu) {
				var jqmenuItem = $(menuItem);
				if(jqmenuItem.attr('name') != 'mailchimp_pulled'){
					jqmenuItem.attr('name', 'mailchimp_pulled');
					jqmenuItem.attr('title', $(this).html());
					
					$.contextMenu.createMenuItem('Loading',{
						title: 'mailchimp_loading',
						icon: '/img/3rd-party/loading.gif'
					}).appendTo($('.context-menu-theme-mailchimp_context_menu'));
					
					var json = $.getJSON($.mailchimp.service_uri+$(this).html(), function(data){
						$('div [title=mailchimp_loading]').remove();
						$.each(data, function(i, item){
							if(item){ var selected = 'selected';} else { var selected = 'unselected'; }
							$.contextMenu.createMenuItem(i,{
								title: escape(i),
								onclick: function(menuItem, menu){
									var email = $('div [name=mailchimp_pulled]').attr('title');
									var jqinner = $(menuItem).children(':first');
									jqinner.css('background-image','url(/img/3rd-party/loading.gif)');
									$.getJSON($.mailchimp.service_uri+email+'/group:'+escape(jqinner.html()),function(data){
										$.each(data, function(i, item){
											if(item){ var selected = 'selected';} else { var selected = 'unselected'; }
											$('div [title='+escape(i)+']').children(':first').css('background-image','url(/img/3rd-party/mailchimp_'+selected+'.gif)');
										});
									});
									return false;
								},
								icon: '/img/3rd-party/mailchimp_'+selected+'.gif'
							}).appendTo($('.context-menu-theme-mailchimp_context_menu'));
						});
					});
				}
				return false;
			},
			icon: '/img/3rd-party/mailchimp_context_menu.jpg'
		}
	}, 
	$.contextMenu.separator
];
jQuery.mailchimp.menu = jQuery.mailchimp.menuDefault;
jQuery.mailchimp.beforeShow = function(){
	//alert('asdf');
}
jQuery.mailchimp.showCallback = function(){
	//alert('show');
}
jQuery.mailchimp.hideCallback = function(){
	$('div [name=mailchimp_pulled]').attr('name', '');
	$('div [name=mailchimp_pulled]').attr('title', '');
	$('.context-menu-separator', $('.context-menu-theme-mailchimp_context_menu')).nextAll().remove();
}


function setCropValues(c){
    $('#cropvalues').val(c.x+'|'+c.y+'|'+c.h+'|'+c.w);
}

function attachCrop(obj){
    if(obj){ var images = $('img', obj); }
    else{ var images = $('img'); }
    images.each(function(item){
        var src = $(this).attr('src');
        if(src.indexOf('/media/photo/') != -1){


            $(this).contextMenu(
            [
                {
                    'Crop': {
                        onclick: function(menuItem,menu) {
                            jQuery.cropimg = this;
                            var src = $(this).attr('src');
                            var tail = src.substring(13, src.length);
                            var asset_id = tail.substring(0, tail.indexOf('.'));
                            var version_id = tail.substring(asset_id.length+1, tail.indexOf('.', asset_id.length+1));
                            var ext = tail.substring(tail.indexOf('.', asset_id.length+1)+1);
                            $.getJSON('/media/versionhw/'+version_id, function(data){
                                $(data).each(function(i,item){
                                    crop(asset_id, version_id, ext, item.PhotoVersion);
                                })
                            });
                            
                        },
                        icon: '/img/crop.png'
                    }
                }
            ],
            {
                theme:'gloss',
                showSpeed:100, 
                hideSpeed:100, 
                showTransition:'fadeIn', 
                hideTransition:'fadeOut'
            });


        }

    });
}

function crop(asset_id, version_id, ext, crop){
    
    if($("#easyOverlay")) { $("#easyOverlay").remove(); }

    $.getJSON('/media/existingcrop/'+asset_id+'/'+version_id, function(data){
        $(data).each(function(i,item){
            var ec = false;
            if(item.Crop){ var ec = item.Crop; }
            $("body").append("<p id='easyOverlay'><a href='javascript:void(0)' class='closeit'>X</a></p>");
            
            $("<img class='Left' id="+asset_id+" src='/media/photo/"+asset_id+".0."+ext+"' alt='' />").appendTo('#easyOverlay').load(function() {
                var imgpos = $(jQuery.cropimg).position();
                //var wide = imgpos.left;
                //var high = imgpos.top;
                var width = $('#easyOverlay img').width();
                if(width > 800){ width = 800; }
                $("#easyOverlay").css({
                    top: '50px',
                    left: '50%',
                    margin: '0px 0px 0px -'+(width/2)+'px',
                    display: 'none',
                    visibility: "visible",
                    position: 'fixed'
                }).fadeIn();
            });
            
            $("<input id='cropvalues' type='hidden' name='"+asset_id+"|"+version_id+"' value='' />").appendTo('#easyOverlay')
            
            $("<input class='Right p5 m10' type='button' value='Crop' />").click(function(){
                $.getJSON('/media/crop/'+$('#cropvalues').attr('name')+'|'+$('#cropvalues').attr('value'), function(data){
                    $(jQuery.cropimg).attr('src', $(jQuery.cropimg).attr('src')+'?'+Math.floor(Math.random()*99999));
                    $("#easyOverlay").fadeOut();
                    jQuery.cropimg = null;
                });
            }).appendTo('#easyOverlay');
            
            if(ec){
                setSelect = [parseFloat(ec.x),parseFloat(ec.y),parseFloat(ec.y)+parseFloat(ec.h),parseFloat(ec.x)+parseFloat(ec.w)];
                $('#'+asset_id).Jcrop({
                    onChange: setCropValues,
                    aspectRatio: parseFloat(crop.width)/parseFloat(crop.height),
                    minSize: [parseFloat(crop.width),parseFloat(crop.height)],
                    setSelect: setSelect,
                    boxWidth: 800, 
                    boxHeight: 600
                });
            } else {
                $('#'+asset_id).Jcrop({
                    onChange: setCropValues,
                    aspectRatio: parseFloat(crop.width)/parseFloat(crop.height),
                    minSize: [parseFloat(crop.width),parseFloat(crop.height)],
                    boxWidth: 800, 
                    boxHeight: 600
                });
            }
            

            
            $("a.closeit").live("click", function(){
                $("#easyOverlay").fadeOut();
            });
            
        })
    });
    
};

function ajaxFileUpload(uploader)
{
	$("#loading")
	.ajaxStart(function(){
		$(this).show();
	})
	.ajaxComplete(function(){
		$(this).hide();
	});

	$.ajaxFileUpload
	(
		{
			url:'/media/upload?ajax',
			secureuri:false,
			fileElementId: uploader.id,
			hiddenElementId: uploader.id+'Hidden',
			dataType: 'json',
			beforeSend:function()
			{
				$("#loading").show();
			},
			complete:function()
			{
				$("#loading").hide();
			},
			success: function (data, status)
			{
				if(typeof(data.error) != 'undefined')
				{
					if(data.error != '')
					{
						alert(data.error);
					}else
					{
						//alert(data.msg);
						$('#' + this.fileElementId).after('<img class="UploadThumb" src="/media/photo/' + data.msg +'.1.jpg" />');
						$('#' + this.fileElementId).remove();
						document.getElementById(this.hiddenElementId).value = data.msg;
					}
				}
			},
			error: function (data, status, e)
			{
				alert(e);
			}
		}
	)
	
	return false;

}


jQuery.extend({
    createUploadIframe: function(id, uri)
	{
			//create frame
            var frameId = 'jUploadFrame' + id;
            
            if(window.ActiveXObject) {
                var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
                if(typeof uri== 'boolean'){
                    io.src = 'javascript:false';
                }
                else if(typeof uri== 'string'){
                    io.src = uri;
                }
            }
            else {
                var io = document.createElement('iframe');
                io.id = frameId;
                io.name = frameId;
            }
            io.style.position = 'absolute';
            io.style.top = '-1000px';
            io.style.left = '-1000px';

            document.body.appendChild(io);

            return io			
    },
    createUploadForm: function(id, fileElementId)
	{
		//create form	
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
		var oldElement = jQuery('#' + fileElementId);
		var newElement = jQuery(oldElement).clone();
		jQuery(oldElement).attr('id', fileId);
		jQuery(oldElement).before(newElement);
		jQuery(oldElement).appendTo(form);
		//set attributes
		jQuery(form).css('position', 'absolute');
		jQuery(form).css('top', '-1200px');
		jQuery(form).css('left', '-1200px');
		jQuery(form).appendTo('body');		
		return form;
    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()        
		var form = jQuery.createUploadForm(id, s.fileElementId);
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;		
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
		{
			jQuery.event.trigger( "ajaxStart" );
		}            
        var requestDone = false;
        // Create the request object
        var xml = {}   
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
		{			
			var io = document.getElementById(frameId);
            try 
			{				
				if(io.contentWindow)
				{
					 xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                	 xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
					 
				}else if(io.contentDocument)
				{
					 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                	xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}						
            }catch(e)
			{
				jQuery.handleError(s, xml, null, e);
			}
            if ( xml || isTimeout == "timeout") 
			{				
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
					{
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );    
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );
    
                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e) 
				{
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);
				//clear up the created form after file uploaded.
                jQuery(io).unbind()

                setTimeout(function()
									{	try 
										{
											jQuery(io).remove();
											jQuery(form).remove();	
											jQuery('#' + s.fileElementId).val('');
											
										} catch(e) 
										{
											jQuery.handleError(s, xml, null, e);
										}									

									}, 100)

                xml = null

            }
        }
        // Timeout checker
        if ( s.timeout > 0 ) 
		{
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try 
		{
           // var io = jQuery('#' + frameId);
			var form = jQuery('#' + formId);
			jQuery(form).attr('action', s.url);
			jQuery(form).attr('method', 'POST');
			jQuery(form).attr('target', frameId);
            if(form.encoding)
			{
                form.encoding = 'multipart/form-data';				
            }
            else
			{				
                form.enctype = 'multipart/form-data';
            }			
            jQuery(form).submit();

        } catch(e) 
		{			
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }
        else{
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        } 		
        return {abort: function () {}};	

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" )
            eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();
			//alert(jQuery('param', data).each(function(){alert(jQuery(this).attr('value'));}));
        return data;
    }
})

/*

var TMCE_Initializer = {
    count : 0,
    run : function(){
        var tot = 0;
        $('.mceSimple').each(function(){
            $(this).attr('class', 'TMCE_Initializer_'+TMCE_Initializer.count);
            //$(this).addClass('TMCE_Initializer_'+TMCE_Initializer.count);
            tot++;
        });
        if(tot>0){
            tinyMCE.init({
            
            	// General options
            	mode : "textareas",
            	theme : "advanced",
            	plugins : "safari",
            
            	// Theme options
            	theme_advanced_buttons1 : "bold,italic,underline,bullist,numlist,link,unlink,|,justifyleft,justifycenter,justifyright,justifyfull",
            	theme_advanced_buttons2 : "",
            	theme_advanced_buttons3 : "",
            	theme_advanced_toolbar_location : "top",
            	theme_advanced_toolbar_align : "left",
            	theme_advanced_resizing : true,
                editor_selector : 'TMCE_Initializer_'+TMCE_Initializer.count
            });
            TMCE_Initializer.count++;
        }
    }
};

*/

/*

jQuery.fn.businessSearch = function(){
    return this.each(function(i){
        var getHTML = function(o){
        	var ret = document.createElement(o.tagName); 
        	for(var i in o) if(i!='tagName') ret[i] = o[i]; 
        	return ret;
        };
        var hiddeninput = getHTML({tagName: 'input', id: 'hidden_' + this.id, name: this.name, type:'hidden'});
        var hiddendiv = getHTML({tagName: 'div'});
        hiddendiv.id = 'BusinessSearchList';
        hiddendiv.style.display = 'none';
        hiddendiv.appendChild(getHTML({tagName: 'ul'}));
        
        this.parentNode.insertBefore(hiddeninput, this);
        this.parentNode.insertBefore(hiddendiv, this);
        this.name = null;
        
        this.onkeypress = function(e){
            $('#BusinessSearchList ul').empty();
            
            var keywords = this.value;
            if(String.fromCharCode(e.which) != '\b'){
                keywords += String.fromCharCode(e.which);   
            }
            else{
                keywords = keywords.substr(0,keywords.length - 1);
            }
            
            if(e.which != 0 && String.fromCharCode(e.which) != '\b'){
                if(keywords.length > 0){
                    var url = "/business/search/?ajax&q="+keywords;
                    $.getJSON(url, function(results){
                        var count = 0;
                        var lastkey = '';
                        var lastvalue = '';
                        for(i in results.b){
                            var lnk = document.createElement('a');
                            lnk.innerHTML = lnk.title = results.b[i];
                            lnk.id = i;
                            lnk.href = "javascript:void(0);";
                            
                            lnk.onclick = function(){
                                document.getElementById(e.target.id).value = this.title;
                                document.getElementById('hidden_' + e.target.id).value = this.id;
                                $('#b21_business_search').attr('class', 'BusinessSearchCheck');
                            };
                            
                            var listElement = document.createElement('li');
                            listElement.appendChild(lnk);
    
                            $('#BusinessSearchList ul').append(listElement);
                            count++;
                            lastkey = i;
                            lastvalue = results.b[i];
                        }
                        
                        var hiddendiv = document.getElementById('BusinessSearchList');
                        if(count == 1 && e.which != 0 && String.fromCharCode(e.which) != '\b'){
                            document.getElementById(e.target.id).value = lastvalue;
                            document.getElementById('hidden_'+e.target.id).value = lastkey;
                            hiddendiv.style.display = 'none';
                            $(this).attr('class', 'BusinessSearchCheck');
                        }
                        else if(count == 0){
                                hiddendiv.style.display = 'none';
                                document.getElementById('hidden_'+e.target.id).value = 0;
                                $(this).attr('class', '');
                        }
                        else{
                            hiddendiv.style.display = 'block';
                            hiddendiv.style.position = 'absolute';
                            hiddendiv.style.width = $('#'+e.target.id).outerWidth() + 'px';
                            hiddendiv.style.left = $('#'+e.target.id).position().left + 'px';
                            hiddendiv.style.top = ($('#'+e.target.id).position().top + $('#'+e.target.id).outerHeight() + 2) + 'px';
                        }
                        
    
                    });
                }
                else{
                    hiddeninput.value = '';   
                    $(this).attr('class', '');
                }
            }
            
        };

        $(this).change(function(e){
            if(hiddeninput.value){
                $(this).attr('class', 'BusinessSearchCheck');
            }
            else{
                $(this).attr('class', '');
            }
        });
        
        $(this).blur(function(e){
            if(hiddeninput.value){
                $(this).attr('class', 'BusinessSearchCheck');
            }
            else{
                $(this).attr('class', '');
            }
            
            setTimeout(function(){
                hiddendiv.style.display = 'none';
            }, 2000);
        });
        
    });
};

*/


var HoverPanel = {
	delayTime : 2000, 
/*	isDisplayed : false, 
	isHovered : false, 
	mouseX : 0, 
	mouseY : 0, 
	info : null, */
	tabsContainerElemExp : '#tabs > ul',

	handle : function(){
/*		this.isHovered = true;
		$('#hoverPanelContent').slideDown();
		$(document).bind('mousemove',HoverPanel.trackMouse);*/
	},
	mouseout : function(){
/*		this.isHovered = false;
		setTimeout('HoverPanel.hide()',this.delayTime);
		//$(document).unbind('mousemove',HoverPanel.trackMouse);*/
	}, 
/*		overPanel : function(){
		var jq = $('#hoverPanel');
		var offset = jq.offset();
		var measure = {
			top : offset.top, 
			left : offset.left, 
			width : jq.outerWidth(), 
			height : jq.outerHeight()
		};
		var hovered = true;
		hovered = (this.mouseX <= (measure.left+measure.width) && this.mouseX >= measure.left);
		hovered = (this.mouseY <= (measure.top+measure.height) && this.mouseY >= measure.top);
		return hovered;
	},
	hide : function(){
		//if(!this.isHovered){			
		if(!this.overPanel()){
			$(document).unbind('mousemove',HoverPanel.trackMouse);
			this.isHovered = false;
			this.isDisplayed = false;
			$('#hoverPanelContent').slideUp();
		}
		//}
	}, 
	trackMouse : function(e){
		e = e || event;
		HoverPanel.mouseX = e.pageX;
		HoverPanel.mouseY = e.pageY;
	},*/
	kill : function(){
		if($('#hoverPanel').attr('hovered')=='no'){
			var h = 43 - parseFloat($('#hoverPanel').outerHeight());
			$('#hoverPanel').animate(
				{ 
					top : h  
				}, 
				850, 
				'swing' 
			);
		}
	}, 
	tabsLinks : function(){
        $('#hoverPanel a').click(function(){
            if(window.location.href.indexOf('/business/console') != -1)
            {
                $(HoverPanel.tabsContainerElemExp).tabs( 'add', $(this).attr('href') + '?ajax', $(this).attr('title') );
                $(HoverPanel.tabsContainerElemExp).tabs( 'select', $(HoverPanel.tabsContainerElemExp).tabs('length') - 1);
                
                window.location.href = '#home';
                return false;
            }
            else
            {
                var tab = $(this).attr('href');
                while (tab.indexOf('/') != -1)
                {
                    tab = tab.replace('/','|');
                }
                href = "/business/console/tab:" + tab + "/name:" + $(this).attr('title');
                window.location.href = href;
                return false;
            }
            
        });
        
		
		//set hover effect
		$('#hoverPanel').hover(
			function(){
				$(this).attr('hovered','yes');
				$(this).animate(
					{ 
						top : 26  
					}, 
					500, 
					'swing' 
				);
			}, 
			function(){
				$('#hoverPanel').attr('hovered','no');
				setTimeout('HoverPanel.kill()', HoverPanel.delayTime);	
			}
		);
		$('#hoverPanel').attr('hovered','no');
		HoverPanel.kill();
		
	} // end tabLinks 
};


var UTIL = UTIL || {};
UTIL.popup = UTIL.popup || {};

UTIL.popup.open = function (href, params)
{
    // Defaults (don't leave it to the browser)
    var defaultParams = {
        "width":       "800",   // Window width
        "height":      "600",   // Window height
        "top":         "0",     // Y offset (in pixels) from top of screen
        "left":        "0",     // X offset (in pixels) from left side of screen
        "directories": "no",    // Show directories/Links bar?
        "location":    "no",    // Show location/address bar?
        "resizeable":  "yes",   // Make the window resizable?
        "menubar":     "no",    // Show the menu bar?
        "toolbar":     "no",    // Show the tool (Back button etc.) bar?
        "scrollbars":  "yes",   // Show scrollbars?
        "status":      "no"     // Show the status bar?
    };

    var windowName = params["windowName"] || "new_window";

    var i, useParams = "";

    // Override defaults with custom values while we construct the params string
    for (i in defaultParams)
    {
        useParams += (useParams === "") ? "" : ",";
        useParams += i + "=";
        useParams += params[i] || defaultParams[i];
    }
    return window.open(href, windowName, useParams);
};
