//NOTE some functions have issues if put inside window.addEvent('domready')

function ajaxUrlPopup(link, e){ //e is the event handler used to figure out the position of the mouse only.
    /*opens a link in an ajax popup
     *requires an empty <div class="pop_up id="pop_up"></div>
     */
	
    $('pop_up').setStyle('display', 'block');
    $('pop_up').setStyle('opacity', 100);
    $('pop_up').setStyle('top', yMousePos - 160);
    
    var ajax_url;
    if ($type(link) == 'element') { // the argument is a link element get the href value
        ajax_url = link.getProperty('href');
    }
    else {
        ajax_url = link;
    } // if url is not with in <a> element use the argument as full url
    new Request.HTML({
        url: ajax_url,
        onRequest: function(){
            $('pop_up').set('html', '<img src=/css/img/ajax-loader.gif />');
        },
        update: $('pop_up'),
		onSuccess: function(){
			ajaxPopupSetup();
			prefilled();
		}
    }).send();
}

if (document.layers) { // Netscape
    document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = captureMousePosition;
} else if (document.all) { // Internet Explorer
    document.onmousemove = captureMousePosition;
} else if (document.getElementById) { // Netcsape 6
    document.onmousemove = captureMousePosition;
}	

// Global variables
xMousePos = 0; // Horizontal position of the mouse on the screen
yMousePos = 0; // Vertical position of the mouse on the screen
xMousePosMax = 0; // Width of the page
yMousePosMax = 0; // Height of the page

function captureMousePosition(e) {
    if (document.layers) {
        // When the page scrolls in Netscape, the event's mouse position
        // reflects the absolute position on the screen. innerHight/Width
        // is the position from the top/left of the screen that the user is
        // looking at. pageX/YOffset is the amount that the user has
        // scrolled into the page. So the values will be in relation to
        // each other as the total offsets into the page, no matter if
        // the user has scrolled or not.
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    } else if (document.all) {
        // When the page scrolls in IE, the event's mouse position
        // reflects the position from the top/left of the screen the
        // user is looking at. scrollLeft/Top is the amount the user
        // has scrolled into the page. clientWidth/Height is the height/
        // width of the current page the user is looking at. So, to be
        // consistent with Netscape (above), add the scroll offsets to
        // both so we end up with an absolute value on the page, no
        // matter if the user has scrolled or not.
        xMousePos = window.event.x+document.body.scrollLeft;
        yMousePos = window.event.y+document.body.scrollTop;
        xMousePosMax = document.body.clientWidth+document.body.scrollLeft;
        yMousePosMax = document.body.clientHeight+document.body.scrollTop;
    } else if (document.getElementById) {
        // Netscape 6 behaves the same as Netscape 4 in this regard
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    }
}

function ajaxPopupSetup(){
	/*
	var myDrag = new Drag.Move('draggable', {
 
	    droppables: '.droppable',
	 
	    onDrop: function(element, droppable, event){
	        if (!droppable) console.log(element, ' dropped on nothing');
	        else console.log(element, 'dropped on', droppable, 'event', event);
	    },
	 
	    onEnter: function(element, droppable){
	        console.log(element, 'entered', droppable);
	    },
	 
	    onLeave: function(element, droppable){
	        console.log(element, 'left', droppable);
	    }
	 
	});

	
	var dragHandle = $$('.popup_handle');
	$('pop_up').makeDraggable({
		handle: dragHandle[0]
	});
	
	var dragElement = $('pop_up');
	//dragElement.setStyle('opacity', .5);
	var dragHandle = $$('.popup_handle');
	handle = dragHandle[0];
	
	var myDrag = new Drag.Move(dragElement, {
		container: dragContainer,
		handle: handle
	});
	*/
} 

ajaxPopUpEvent = function(e){
	e.stop();
	ajaxUrlPopup(this, e);
}

function fadePopup(){
	var fade_out = "$('pop_up').fade('out')";
	setTimeout(fade_out, 2000);		
}

function loginRequired(e,runEventFunction){  
	
	if ($('user_id').value == '') {
		// the user has not logged in;	
		e.stop();
		ajaxUrlPopup('/login/ajaxLogin/', e);	
	}else
		runEventFunction();  //adding the event if the user is logged in.
}

function fadeOutPopup() { //fades then display none popups
	var fade_out = $('pop_up').fade('out');
	setTimeout(fade_out,4000);
	
}

window.addEvent('domready', function(){
	prefilled();
	
	$$('div[title=coupon]').addEvent('click', function(event){
		
		if ($('user_id').value == '') {
				// the user has not logged in;	
				ajaxUrlPopup('/login/ajaxLogin/', event);
				return false;
				
			}
		var thisCoupon = this;

		var url = '/bin/ajax_';
		var saving = true;
		if (thisCoupon.hasClass('delete')) {
			saving = false;
			url += 'unSave';
		} else {
			url += 'save';
		}
		url += 'Coupon/' + this.get('couponid');
		
		event.stop();
		
		var a = new Request({
			method: 'get',
			url: url,
			onComplete: function(response){
				var currentNumCoupons = $('num_saved_coupons').get('text').toInt();
				if (response == '1') 
					if (saving) {
						thisCoupon.set('class', 'delete');
						thisCoupon.set('alt', 'Delete from your smartphone');
						setAltText(thisCoupon);
						$('num_saved_coupons').set('text', currentNumCoupons+1); 
					}
					else {
						thisCoupon.set('class', 'save');
						thisCoupon.set('alt', 'Save to view on your smartphone');
						setAltText(thisCoupon);
						$('num_saved_coupons').set('text', currentNumCoupons-1);
					}
				else 
					alert('There was a database error, please try again. It is possible this was by using multiple browsers on the site at once. If this is the case, please log in and out to fix your cookies :)');
			}
		}).send();
		
	});
	
	/*increment coupon share stats*/
	if ( $('user_id').value != '' ){
		
			$$('.share_action').addEvent('click', function(){
		    	new Request({ url: '/profile/incrementShareStats'}).send();

		});
	}


	/*FEEDBACK FORM*/
	var feedback_formHeight = 352;
	var feedback_formHTML = $('feedback_form').get('html');
	$('feedback_form').setStyles({'height': 0, 'display': 'block'});
	$('feedback_button').addEvent('click', function(){
		if(this.hasClass('down')){
			this.set('class', 'up');
			$('feedback_form').tween('height', feedback_formHeight);
		} else {
			this.set('class', 'down');
			$('feedback_form').set('html', feedback_formHTML);
			prefilled();
			$('feedback_form').tween('height', 0);
		}
	});

	$('feedback_form').addEvent('submit', function(e){
		e.stop();
		var ThisForm = this;
		this.set('send', {
			onRequest: function(){
				ThisForm.set('html', '');
			},
			onComplete: function(response){
				ThisForm.set('html', response);
				ThisForm.tween('height', 45);
			}
		});
		this.send();
	});
	
});
