/*
  developer: media 27, inc.
  extended functionality: age verification
   
*/
window.addEvent('domready', function() {
    
	/*
    Element.implement({
		addLiveEvent: function(event, selector, fn){
			
			this.addEvent(event, function(e)
			{
				var t = $(e.target);
				if (!t.match(selector)) return false;
				fn.apply(t, [e]);
			}.bindWithEvent(this, selector, fn));
		}
	});
	*/
	
	/*
    * If visitor age is not valid, add an intercept event to each
    * shopping link to force the verification window.
    */
    globalSession = new session();
    if( !globalSession.isUserOver18() )
         globalSession.addClickInterceptEvents();
		 
	// intercept images found in scroll containers
	globalSession.interceptImageLoader();
    
    // add events to search buttons
    globalSession.addSearchClickEvents();

    // request country data if necessary
    globalSession.requestInsertAvailableCountries();
     
});
window.addEvent('load', function() {

	//$(document.body).addLiveEvent('click', 'a.isShop', function(e){
	//	alert('click'); 
	//});

	// load any images we intercepted
	globalSession.onLoadInterceptedImages();
	
});

var session = new Class({  

	alinks: {},
	isAgeSet:0,
	isVerifyEnabled:0,
	lastClickedShopUrl:'',
	selectedDay:null,
	selectedMonth:null,
	selecteYear:null,
	arr_interceptedElements:Array(),
	arr_interceptedImages:Array(),
	
        	
    isUserOver18: function() {    
          
		  // auto validate if the verifier is off
		  if(this.isVerifyEnabled!=1)
		  	return true;
			
		  var c = this.getCookie("validage");
		  if( c && c!='0' )
              return true;
    
          return false;        
    },
	grayOut: function(vis, options) {

		  // Pass true to gray out screen, false to ungray
		  // options are optional.  This is a JSON object with the following (optional) properties
		  // opacity:0-100         // Lower number = less grayout higher = more of a blackout 
		  // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
		  // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
		  // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
		  // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
		  // in any order.  Pass only the properties you need to set.
		  var options = options || {}; 
		  var zindex = options.zindex || 50;
		  var opacity = options.opacity || 70;
		  var opaque = (opacity / 100);
		  var bgcolor = options.bgcolor || '#000000';
		  var dark=document.getElementById('darkenScreenObject');
		  if (!dark) {
			// The dark layer doesn't exist, it's never been created.  So we'll
			// create it here and apply some basic styles.
			// If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
			var tbody = document.getElementsByTagName("body")[0];
			var tnode = document.createElement('div');           // Create the layer.
				tnode.style.position='absolute';                 // Position absolutely
				tnode.style.top='0px';                           // In the top
				tnode.style.left='0px';                          // Left corner of the page
				tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
				tnode.style.display='none';                      // Start out Hidden
				tnode.id='darkenScreenObject';                   // Name it so we can find it later
			tbody.appendChild(tnode);                            // Add it to the web page
			dark=document.getElementById('darkenScreenObject');  // Get the object.
		  }
		  if (vis) {
			// Calculate the page width and height 
			if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
				var pageWidth = document.body.scrollWidth+'px';
				var pageHeight = document.body.scrollHeight+'px';
			} else if( document.body.offsetWidth ) {
			  var pageWidth = document.body.offsetWidth+'px';
			  var pageHeight = document.body.offsetHeight+'px';
			} else {
			   var pageWidth='100%';
			   var pageHeight='100%';
			}   
			//set the shader to cover the entire page and make it visible.
			dark.style.opacity=opaque;                      
			dark.style.MozOpacity=opaque;                   
			dark.style.filter='alpha(opacity='+opacity+')'; 
			dark.style.zIndex=zindex;        
			dark.style.backgroundColor=bgcolor;  
			dark.style.width= pageWidth;
			dark.style.height= pageHeight;
			dark.style.display='block';				 
		  } else {
			 dark.style.display='none';
		  }
	},
    setValidAge: function() {    
          //document.cookie="validage=1"; 
		  var date = this.selecteYear+':'+this.selectedMonth+':'+this.selectedDay;
		  Cookie.write('validage', date, {path: '/'}); 
    }, 
	validateDay: function(element,index) {
		this.selectedDay = element.options[index].value;
	},
	validateMonth: function(element,index) {
		this.selectedMonth = element.options[index].value;
	},
	validateYear: function(element,index) {
		this.selecteYear = element.options[index].value;
	},
	validateAge: function() {
		/*
		var valueMonth = $('selectMonth').get('value');
		var valueDay = $('selectDay').get('value');
		var valueYear = $('selectYear').get('value');

		if(!valueMonth || valueMonth=='' || valueMonth==undefined || valueMonth=='month')
			alert('Please select the month you were born');
		else if(!valueDay || valueDay=='' || valueDay==undefined || valueDay=='day')
			alert('Please select the day you were born');
		else if(!valueYear || valueYear=='' || valueYear==undefined || valueYear=='year')
			alert('Please select the year you were born');
		else {
		*/
		if(!this.selectedMonth || this.selectedMonth=='' || this.selectedMonth==undefined || this.selectedMonth=='month')
			alert('Please select the month you were born');
		else if(!this.selectedDay || this.selectedDay=='' || this.selectedDay==undefined || this.selectedDay=='day')
			alert('Please select the day you were born');
		else if(!this.selecteYear || this.selecteYear=='' || this.selecteYear==undefined || this.selecteYear=='year')
			alert('Please select the year you were born');
		else {
	
			// allow 1 age validation per session
			this.setAgeLock(1); // incidentally, the value is meant to set the property to true, not to indicate 1 validation
		
			// evaluate entry
			if( this.isAgeValid(this.selectedMonth,this.selectedDay,this.selecteYear) ) {
				// accept
				this.setValidAge();

				// remove all intercepts
				var anchors = $(document.body).getElements('a');
				for(i=0; i<anchors.length; i++)
				{
					if( anchors[i].href.indexOf('shop')!=-1 )
					{
						anchors[i].setProperty('onclick', '');
					}
				}

				// retrieve the stored link
				var url = this.alinks[this.lastClickedShopUrl];
				// redirect
				parent.window.location.href = url;
				
			} else {
				// inject the page with denied
				//$(document.body).innerHTML = '<div>hello</div>';
				//var updateMe = window.parent.$('body');
				//updateMe.set('html','<h3>Loading ...</h3>');
				//updateMe.load('verify.php');
				
				// make sure there isn't a value in the session cookie
				Cookie.dispose('validage');
				
				parent.window.location.href = '/sorry-underage';
				//alert('Sorry, you are not old enough to enter our shopping website.');
			}
		
			// clear the validation values so they can be changed if necessary
			//this.selectedDay = null;
			//this.selectedMonth = null;
			//this.selecteYear = null;
		
			// close window : do this last so the parent can still be accessed
			parent.Mediabox.close();
			
		}
	},
	setAgeLock: function(limit) {
		Cookie.write('ageset', limit, {path: '/'});
	},
	isAgeLocked: function() {
		var c = this.getCookie("ageset");

		  if( c && parseInt(c)>=1 )
              return true;
    
          return false;   
	},
	isAgeValid: function(m,d,y) {
		
		var min_age = 18;
		var max_age = 122;
		
		var this_date=new Date();
		var this_year = this_date.getFullYear();
		var this_month = this_date.getMonth()+1;
		var this_day = this_date.getDate();

		var min_year = this_year - max_age;
		var max_year = this_year - min_age;
		
		if ( (y > min_year) && (y < max_year) ) {
			return true;
		} else if ( (y == max_year) && 
				  ( (m < this_month) ||
				   ( (m == this_month) && (d <= this_day) ) ) ) {
			return true;
		} else if ((y == min_year) &&
				  ((m > this_month) ||
				   ((m == this_month && (d > this_day))))) {
			return true;
		} else {
			return false;
		}

	},
	shopClick: function(e) { 

		  // Set the idenifier in storage
		  this.lastClickedShopUrl = e.getProperty('identifier');
	
          // Check the age verification status in case it was changed
		  if( !globalSession.isUserOver18() )
		  {

			  // add div tag if not present
			  //var newElement  = new Element('div', {id:'ageverify', text:mhtml.vars['ageverify']});
			  //var targetElement = $('mb_ageverify');
			  //newElement.inject(targetElement, 'top');

			  // popup age verfication window
			  if(!globalSession.isAgeLocked())
			  		$('ageverify').fireEvent('click');
			  else
			  		window.location.href = '/sorry-underage'; // we are the parent
					//alert('Sorry, you are not old enough to enter our shopping website.');
					
			  // pass the popup all the data required so the user
			  // can be proceed to the shop after validation
			  
		  } else {
			  /*
			  	This exists in case the click events are still being intercepted
				even after age has been validated. The intercept events should have
				been removed, but since they are still active, use the stored values
				in the click array to redirect the user.
			  */
			  // redirect
			  // retrieve the stored link
				var url = this.alinks[this.lastClickedShopUrl];
				// redirect
				parent.window.location = url;
		  }        
    },
    getCookie: function(field) {  
          
		  //var searchFor = field + "="
          //var returnValue = null;
          
		  var returnValue = Cookie.read(field);
		  /*
          if (document.cookie.length > 0) {
            // set start index
            offset = document.cookie.indexOf(searchFor)    
            // if cookie exists
            if (offset != -1) { 
              offset += searchFor.length
              // get end index
              end = document.cookie.indexOf(";", offset);
              // set end index
              if (end == -1) end = document.cookie.length;
              
              returnValue=unescape(document.cookie.substring(offset, end))
            }
              
          }
		  */
		  
         return returnValue;
    },
	testClick: function(e) {
		alert(e.href);
	},
	// Removes image lists before they can load.
	// The images are delayed until after everything
	// else has loaded.
	interceptImageLoader: function() {
		
		// apply cache loader to image lists
		
		var anchors = $(document.body).getElements('li a img');
	
		// set local var that can be used inside the FOR statement
		var _this = this;
	
		for(i=0; i<anchors.length; i++)
		{
			// store the element
			_this.arr_interceptedElements.push(anchors[i]);
			// store the individual images
			_this.arr_interceptedImages.push(anchors[i].src);
			
			// apply busy loader to the image
			// SKIP busy loader. It's also applying to an invisible image. Just remove image
			anchors[i].src = ''; // './/media/images/bigloading.gif';
			// remove alt tag to get it out of the display
			anchors[i].alt = '';
			
		}
		
		// remember, the images that were removed will be applied onLoad
		
	},
	// images that were intercepted at startup are loaded here
	onLoadInterceptedImages: function () {
		
		// set local var that can be used inside the image loader
		var arr_elements = this.arr_interceptedElements;
		
		if(this.arr_interceptedImages && this.arr_interceptedImages.length>0)
		{

			// begin background image loading
			var myImages = new Asset.images(this.arr_interceptedImages, {
				onProgress: function(counter, index, source) {

						// retrieve the original element
						var e = arr_elements[index];
						
						// set element property in order to apply loaded image
						e.setProperty('src', source);
						
					}
			});
		
			// clear the intercepted arrays
			this.arr_interceptedImages = Array();
			this.arr_interceptedElements = Array();
		}
	},
    addSearchClickEvents: function() {

        var search = $(document.body).getElements('.searchBtn');
        
        for(i=0; i<search.length; i++)
        {
            search[i].addEvent('click', function(){
                globalSession.applyBusyIcon(this);  
                //return false;
            }); // .bind(this) bind this to prevent scope error
        }
        
    },
    requestInsertAvailableCountries: function() {
    
        var country_box = document.getElementById("country_box"); 
        
        if(country_box)
        {     
            
            // AJAX
            var myRequest = new Request({
                method: 'get', 
                url: 'request_countries.php',
                
                onSuccess: function(responseText){
                    country_box.innerHTML = responseText;
                },
                onFailure: function(){ 
                    country_box.innerHTML = 'Sorry, your request failed.';
                }
                
                });
            myRequest.send('submit=1');
        }
        
    },
    addClickInterceptEvents: function() {
        
        // attach click events
 
		var anchors = $(document.body).getElements('a');
		for(i=0; i<anchors.length; i++)
		{
			if( anchors[i].href.indexOf('shop')!=-1 )
			{
				//generate identifier
				var randomnumber=Math.floor(Math.random()*100);
				var identifier = 'a'+String(randomnumber);
				// add identifier
				anchors[i].setProperty('identifier', identifier);
				// store original link
				this.alinks[identifier] = anchors[i].href;
				// deactivate link (but keep status bar display)
				//anchors[i].setProperty('onclick', 'globalSession.shopClick(this);return false;');
				anchors[i].addEvent('click', function(){globalSession.shopClick(this);return false;} );
				//anchors[i].setProperty('href', '#');

			}
		}
		// add div tag
		document.getElementById("mb_ageverify").innerHTML = mhtml.vars['ageverify'];
    },
    applyBusyIcon: function(element) {
        // get parent
        var parent = element.getParent();
        // replace child element with busy icon
        //parent.set('html','&nbsp;searching...&nbsp;<img src="./media//media/images/busy_small.gif" width="16" height="16" border="0" >');
        parent.appendHTML(' &nbsp;searching...&nbsp; <img src=".//media/images/busy_small.gif" width="16" height="16" border="0" >');
    }
});

(function(){ //encapsulate this logic so we don't polute the global namespace

  Element.implement({     
    appendHTML: function(newhtml) {            
        
        //return this.adopt(new Element('div', {html: newhtml}).getChildren()); 
        
        var temp=new Element('div');
        temp.set('html',newhtml);
        this.adopt(temp.childNodes);
    
        return this;
    } 
  });
  
})();


    
