/*  /_js/site.js  sitewide javascript facilitated functionality */

try { var $j = jQuery.noConflict(); } catch (e) {
	var errMsg = 'Got ' + e + ' : this page depends on jQuery 1.2.1 library expected @_js/lib/jquery.js ';
	alert( errMsg ); throw( errMsg );
}
// Flash playback vars
var AC_FL_RunContent, DetectFlashVer = 0; 

$j( function(){ Doc.init() } );

var Doc = { ver:'0.1',

	init: function( ) {
		this.setup();
		this.initPage();
		this.log ? console.log( '> Doc.init done: timer ? ' ):0;
	},
	setup: function() {
				
		this.pathParts = location.pathname.split( '/' );

//  document name without the file type extension
 		this.name = this.pathParts.pop().split( '.' )[0];

		this.name == '' ? this.name = 'index':0;
	
		this.docDir = this.pathParts.pop();

		this.dbg = ( location.hostname == '' || location.hostname == 'localhost' ||
													location.hostname == 'b.mekano.net' ) ? true : false;
//		this.dbg = 1;
		if ( this.dbg && ( typeof console !== 'undefined' ) ) {  this.log = 1; }
		this.log ? console.log ( '> Doc.setup: '
					+ ' Doc.ver:' + this.ver + ' Doc.name: '  + this.name
			+ ' Doc.pathParts: '  + this.pathParts
			+ ' Doc.pathParts.length: '  + this.pathParts.length
			+ ' Doc.docDir: '  + this.docDir + ' location.hostname: "' + location.hostname + '"' ):0;
	},
	initPage: function() { this.log ? console.log( '< Doc.initPage ' + this.name ):0;

		this.adjustPage(); window.onresize = function() { Doc.adjustPage() };

		if ( this.name != 'index' ) { this.appendHomeBtn(); }

		this.setupForms();
		
		switch ( this.name ) {
			case 'index':
// 6/11/09
				if ( this.docDir == 'referral' ) 
                { 
                    $j("#submit_btn").hover(
                      function () { $j(this).css( 'background-position', 'left bottom' ); },
                        function () { $j(this).css( 'background-position', 'left top' ); } );

                    $j('#submit_btn').click( function() {   
                        return submitReferralForm();
                    } );

                    break; 
                }
	
				this.setupHomeBanner();
				
				$j('#buyer_demo_btn').click( this.buyerDemo );
				$j('#product_demo_btn').click( this.productDemo );
				$j('#store_demo_btn').click( this.storeDemo );				
				window.onload = this.preloadImages;
				break;
			case 'buyer':
				$j('#demo_btn').click( this.buyerDemo );
				$j('#demo_btn2').click( this.buyerDemo );
				break;
			case 'product':
				$j('#demo_btn').click( this.productDemo );
				break;
			case 'store':
				$j('#demo_btn').click( this.storeDemo );
				break;
			case 'demos':
				$j('#buyer').click( this.buyerDemo );
				$j('#product_ov').click( this.productDemo );
				$j('#product_ll').click( this.productDemo_ll );
				$j('#product_ft').click( this.productDemo_ft );
				$j('#store').click( this.storeDemo );				
				break;
			case 'contact':
				$j("#submit_btn").hover(
				  function () { $j(this).css( 'background-position', 'left bottom' ); },
				  	function () { $j(this).css( 'background-position', 'left top' ); } );

				$j('#submit_btn').click( function() {
// contact_form FORM SUBMIT, validate
// 			document.forms.contact_form.submit();
                    return submitContactForm();
				});			
// enterKey trapping and form submitting
				$j('#phone,#name_last,#email').keyup( function ( e ) {
					if ( e.which == 13 ) { 
                        return submitContactForm();
                    };
//					Doc.log ? console.log( '> Key: ' + e.which ):0;
				});
				$j('#name_first').focus();
				this.setupContactBanner();
				this.log ? console.log ( '@initPage switch Doc.name: ' +  this.name ):0;
				break;
			case 'getstarted':
				$j('#submit_btn').hover(
				  	function () { $j(this).css( 'background-position', 'left bottom' ); },
				  		function () { $j(this).css( 'background-position', 'left top' ) } );
		
				$j('#submit_btn').click( function() {	
// register_form FORM SUBMIT, validate before
// 			document.forms.register_form.submit();
                    return submitRegisterForm();
				} );
// enterKey trapping and form submitting
				$j('#phone,#name_last,#email,#ref_company,#promo_code').keyup( function ( e ) {
					if ( e.which == 13 ) { 
                        return submitRegisterForm();
                    };
				});
				$j('#name_first').focus();
				this.log ? console.log ( '@initPage switch Doc.name: ' +  this.name ):0;
				break;
			default:
				this.log ? console.log ( '@initPage  default switch Doc.name: ' + this.name +' URL: '+  location ):0;
		};	 
		
		( this.dbg && ! $j.browser.msie ) ? this.appendXmlCheckBtn():0;
		this.log ? console.log( '> Doc.initPage done'  ):0;
	},

	setupForms: function() { 
		this.initUCform();
		this.initVMform();
		this.initEmailform();
	},

// user center
	initUCform: function() {
		$j('#user_login').hover( function(){ $j(this).css( 'color', 'rgb(255,112,0)' ); },
										function(){ $j(this).css( 'color', 'rgb(0,0,0)' ); } );
		$j('#user_login').click( function() {
			var c_btn = this;
			var callBack = function() { $j( c_btn ).toggleClass( 'topmenu_selected' );
				if ( $j('#uc_login_box').css( 'display' ) != 'none' ) { $j('#username_uc').focus(); }
			};
			$j('#uc_login_box').toggle( 500, callBack );
			$j('#vmail_login').slideUp( 500 );
			$j('#sidemenu_email').slideUp( 500 );
			return false;
		});
		
		$j('#go_btn_uc').hover( function () { $j(this).css( 'background-position', '0 -22px' ); },
									function () { $j(this).css( 'background-position', "0 0" ); } );
		$j("#go_btn_uc").click( function () {
// ucform FORM SUBMIT, validate np here or form.onsubmit
//			document.forms.ucform.submit();
            return submitUCForm();
		});
// enterKey code is 13
		$j('#username_uc,#password_uc').keyup( function ( e ) {
			if ( e.which == 13 ) { 
//				document.forms[ 'ucform' ].submit(); 
                return submitUCForm();
            };
  		});
	},

// vmail box customer login
	initVMform: function() {
		$j('#customer_login').hover( function () { $j(this).css( 'color', 'rgb(255,112,0)' ); },
										function () { $j(this).css( 'color', 'rgb(0,0,0)' ); } );
		$j('#customer_login').click( function () {
			if ( $j( '#vmail_login' ).css( 'display' ) == 'none' ) {
				$j('#vmail_login').slideDown( 500, function(){ $j( '#username' ).focus(); } );
				$j('#sidemenu_email').slideUp( 500 );
				$j('#uc_login_box').hide( 500 );
				$j('#user_login').removeClass( 'topmenu_selected' );
			} else {
				$j('#vmail_login').slideUp( 500 );
			}
			return false;
		});
		$j('#go_btn').hover( function () { $j(this).css( 'background-position',  '0 -32px' ); },
										function () { $j(this).css( 'background-position',  'left top' ); } );
		$j('#go_btn').click( function () {
// vmform FORM SUBMIT, validate np here
// 			document.forms.vmform.submit();
 			document.forms[ 'vmform' ].submit();
		} );
// enter key trapping
		$j('#username,#password').keyup( function ( e ) {
			if ( e.which == 13 ) { 
				document.forms[ 'vmform' ].submit(); };
//						Doc.log ? console.log( '> Key: ' + e.which ):0;
  		});
	},
	
// 'email this page'
	initEmailform: function() {
		$j("#email_show").hover( function () { $j(this).css( 'color', 'rgb(255,112,0)' ); },
									function () { $j(this).css( 'color', 'rgb(0,0,0)' ); } );
		$j("#email_show").click( function () {
			$j("#sidemenu_email").slideDown( 500, function(){ $j("#recipient_email").focus() } );
			$j("#uc_login_box").hide( 500 );
			$j("#user_login").removeClass("topmenu_selected");
			$j("#vmail_login").slideUp( 500 );
			return false; }
		);
		$j("#email_hide").hover( function () { $j(this).css( 'color', 'rgb(255,112,0)' ); },
									function () { $j(this).css( 'color', 'rgb(0,0,0)' ); } );
		$j("#email_hide").click( function () { $j("#sidemenu_email").slideUp(); return false; } );

		$j("#send_btn").hover( function () { $j(this).css( 'background-position',  'left bottom' ); },
									function () { $j(this).css( 'background-position',  'left top' ); } );
		$j("#send_btn").click( function () {
// 'email this' FORM SUBMIT, validate np before
//			document.forms.email_page.submit();
            return submitEmailPageForm();
		});
// enter key trapping
		$j('#recipient_email,#recipient_name,#sender_email,#sender_name').keyup( function ( e ) {
			if ( e.which == 13 ) { 
                return submitEmailPageForm();
            };
  		});
//		this.log ? console.log( '> Doc.initEmailform'  ):0;
	},
	     
	demoWindow: undefined,
	openWindow: function( URL, w, h, name ) { 
				// Fudge factors for window decoration space.? w += 32; h += 96;
				//			var wleft = (screen.width - w) / 2; var wtop = (screen.height - h) / 2;
		var scr_w = screen.availWidth;
		var scr_h = screen.availHeight;
			var wleft = (scr_w - w) / 2;
			var wtop = (scr_h - h) / 2;
			
			if ( name == undefined ) { name = 'demo'}
//		if ( Doc.demoWindow ) { Doc.demoWindow.close(); };
		if ( this.demoWindow ) { this.demoWindow.close(); };
		
		var ScrollAndRes ='scrollbars=0,resizable=0'; 
		if ( URL == 'demos/store/index.html' ) { ScrollAndRes ='scrollbars=1,resizable=1'; }
			
			this.demoWindow = window.open( URL, name, 
											'width=' + w + ',height=' + h + ',' +
											'left=' + wleft + ',top=' + wtop + ',' +
						' location=no, menubar=no, status=no, toolbar=no, ' + ScrollAndRes );
			// ?Just in case width and height left & top are ignored
//			this.demoWindow.resizeTo( w, h ); this.demoWindow.moveTo( wleft, wtop );
			this.demoWindow.focus();
		window.onunload = function() { if ( Doc.demoWindow ) { Doc.demoWindow.close(); }; };
			return true;
	},
	buyerDemo: function() {
		var	demoURL = 'demos/buyer/demo.html';	
		var width = 1014;
		var height = 680;
//		left=30
//		var winName = 'demo';
// 		this.openWindow( demoURL, 1014, 680, winName );
		Doc.openWindow( demoURL, width, height );
		return false;
	},
	
	productDemo: function() {
		var	demoURL = 'demos/product/index.html';	
		var width = 1016;
		var height = 713;
		Doc.openWindow( demoURL, width, height );
		return false;
	},
	productDemo_ll: function() {
		var	demoURL = 'demos/line_lists/index.html';
		var width = 1016;
		var height = 713;
		Doc.openWindow( demoURL, width, height );
		return false;
	},
	productDemo_ft: function() {	
		var	demoURL = 'demos/fit_trend/index.html';	
		var width = 1016;
		var height = 713;
		Doc.openWindow( demoURL, width, height );
		return false;
	},
	
	storeDemo: function() {
		var	demoURL = 'demos/store/index.html';
		var width = 920;
		var height = 630;
		Doc.openWindow( demoURL, width, height );
		return false;
	},
	
	appendHomeBtn: function() {
		var home_btnClass = 'home_btn'; //		var home_btnID = 'home_btn';
		$j( '#branding' ).append( '<div class="' + home_btnClass + '"></div>' );
		$j( 'div.' + home_btnClass ).click(  function() { window.location = './index.aspx';  } );
	},
	
	getWindowSize: function() {

	  if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	  } else if( document.documentElement && 
					( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
			{
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	  }
	  return [ myWidth, myHeight ];
	},
	
	adjustPage: function() {

		var pageHeight = $j( '#page' ).height();
		
		var wHeight = this.getWindowSize()[1];
	
		this.log ? console.log( '• Doc.adjustPage page: ' + pageHeight + ' window: ' + wHeight):0;

		if ( pageHeight <= wHeight ) {
			var justifier = 'justifier';
			$j( '#footer' ).before( '<div id="' + justifier + '"></div>' );
			$j( '#'+ justifier ).css( 'height', wHeight - pageHeight + 1 + 'px' );
		}
	},

	preloadImages: function() {
/*		focus section banners  div#banner.buyer div.buyer div.product div.store */
		var classNamess = [ 'focus_buyer', 'focus_product', 'focus_store' ];
		
		for ( var cl in classNamess ) {
				$j( 'body' ).append( '<div class="noDisplay ' + classNamess[ cl ] + '" ></div>' );
		}
		Doc.log ? console.log( '>• Doc.preloadImages : ' ):0;
	},
	
	setupHomeBanner: function() {
		var requiredMajorVersion = 8;		// Major version of Flash required
		var requiredMinorVersion = 0;		// Minor version of Flash required
		var requiredRevision	 = 0;		// Revision of Flash required

		var altBgImg = 'url("_img/home/banner_home_still.jpg")';
		var homeBannerHTML = '';
		
		//var	srcFile = "_img/home/banner_home.swf";
		// file type ie. '.swf' appended by AC_RunActiveContent.js ?!
 		var	srcFile = '_img/home/banner_home';

//	if ( this.AC_FL_RunContent == 0 || DetectFlashVer == 0) {
	if ( window.AC_FL_RunContent == 0 || window.DetectFlashVer == 0) {

		alert("This page requires AC_RunActiveContent.js file, expected @_js/lib/AC_RunActiveContent.js");
	} else {
		var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
		if( hasRightVersion ) {

			homeBannerHTML = AC_FL_GenHTML(
			'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0',

			'width', '860',
			'height', '112',
// embed
			'src', srcFile,
// param			
			'movie', srcFile,
			'id', 'banner_swf',
			'name', 'banner_swf',
			'allowScriptAccess','sameDomain',
			'bgcolor', '#ffffff',
			'quality', 'best',
			'align', 'middle',
			'salign', '',
			'play', 'true',		
			'loop', 'true',
			'scale', 'noscale',
			'wmode', 'window',
			'menu', 'true',
			'allowFullScreen','false',
			'devicefont', 'false',
			'pluginspage', 'http://www.macromedia.com/go/getflashplayer'
			);

			Doc.log ? console.log ( '• #banner swf: ' +  homeBannerHTML ):0;				
	
			$j( '#banner' ).html( homeBannerHTML );
		} else { $j( '#banner' ).css( 'background-image', altBgImg ); }
	}
	},
	
	setupContactBanner: function() {
// #banner bg fades							 
		this.imgIndex = 0;
		
		$j( '#banner' ).click( function(  ){

			var imgFiles = [ 'banner-contact1.jpg', 'banner-contact2.jpg', 'banner-contact3.jpg' ];
			
			Doc.log ? console.log ( '• #banner click: ' +  Doc.imgIndex ):0;				

			Doc.imgIndex++; if ( Doc.imgIndex >= imgFiles.length ) { Doc.imgIndex = 0 };
			
//			var newImg = imgFiles[ Doc.imgIndex ];
			var bgURL = 'url(_img/'+ imgFiles[ Doc.imgIndex ] +')';
	
			var curInterval = function() {
				var min = 500;
				var r = Math.round( Math.random() * 10 ) * 300;
				return min + r;
			};
			var callBack = function() {
				$j( this ).css( 'background-image', bgURL );
				$j( this ).fadeIn( curInterval(), function(){  $j( this ).click() } );
			};
			$j( this ).fadeOut( curInterval() ,  callBack );
		 });
	},
	
	setExtLinks: function( tag ) { //  if ( typeof tag =='undefined' ) { tag='a' }	
		$j("a[@rel='external nofollow']").click( function() {
			var response = confirm( 'This link will open external window with the following location: ' + this.href );
			if ( response ) window.open( this.href );
			return response;
		});
	},
	appendXmlCheckBtn: function() { // return false;
		var xml_btnID = 'xml_check_btn';
		var confirm_prompt = '? xml check';
		var validator_URL = 'http://validator.w3.org/check?uri=referer';
		
		$j( 'body' ).append( '<div id="' + xml_btnID + '"></div>' );
		
		$j( "#" + xml_btnID ).click(  function() {
						confirm( confirm_prompt ) ? window.open( validator_URL ):0;  });
			
		this.log ? console.log( '> Doc.appendXmlCheckBtn xml_btnID: ' + $j( xml_btnID ) ):0;
	},
	
	tmp: ( typeof console !== 'undefined' ) ? console.log ( '$> Doc.new' ):0,
	dbg: false, log: false 
};

// 	 $("input[type='textarea']").keypress( function (e) {
//   		if ( e.which == 32 || (65 <= e.which && e.which <= 65 + 25) || (97 <= e.which && e.which <= 97 + 25))
//   			{	var c = String.fromCharCode( e.which );
//   			Doc.log ? console.log( '> Doc.filterEnterKey: ' + c ):0;
//   				}
//   		});

////////////////////////////////////////////////////////////////////////////////
//                  Javascript Form Validation Routines                       //
////////////////////////////////////////////////////////////////////////////////
function submitUCForm()
{
    var validUsername = true;
    var validPassword = true;
    var theForm = document.forms['ucform'];
    var inputValue = theForm.username_uc.value;
    if(inputValue == null || inputValue == "")
    {
        validUsername = false;
    }
    inputValue = theForm.password_uc.value;
    if(inputValue == null || inputValue == "")
    {
        validPassword = false;
    }
    if(!validUsername && !validPassword)
    {
        alert("Please enter a valid Username and Password");
        return false;
    }
    else if(!validUsername)
    {
        alert("Please enter a valid Username");
        return false;
    }
    else if(!validPassword)
    {
        alert("Please enter a valid Password");
        return false;
    }
    theForm.submit();
    return true;
}

////////////////////////////////////////////////////////////////////////////////
function submitEmailPageForm()
{
    var allFieldsValid = true;
    var theForm = document.forms['email_page'];
    var inputValue = theForm.recipient_email.value;
    if(inputValue == null || inputValue == "")
    {
        allFieldsValid = false;
    }
    inputValue = theForm.recipient_name.value;
    if(inputValue == null || inputValue == "")
    {
        allFieldsValid = false;
    }
    inputValue = theForm.sender_email.value;
    if(inputValue == null || inputValue == "")
    {
        allFieldsValid = false;
    }
    inputValue = theForm.sender_name.value;
    if(inputValue == null || inputValue == "")
    {
        allFieldsValid = false;
    }
    
    if(!allFieldsValid)
    {
        alert("Please enter a value for all fields marked with an '*' ");
        return false;
    }
    theForm.submit();
    return true;
}

////////////////////////////////////////////////////////////////////////////////
function submitContactForm()
{
    var theForm = document.forms['contact_form'];
    theForm.submit();
    return true;
}

////////////////////////////////////////////////////////////////////////////////
function submitRegisterForm()
{
    var theForm = document.forms['register_form'];
    theForm.submit();
    return true;
}

////////////////////////////////////////////////////////////////////////////////
function submitReferralForm()
{
    var theForm = document.forms['refer_form'];

    var allFieldsValid = true;
    var message = "Please enter a value for the following fields:\n";
    
    var inputValue = theForm.r_first_last.value;
    if(inputValue == null || inputValue == "")
    {
        message = message + "- Your First and Last Name\n";
        allFieldsValid = false;
    }
    inputValue = theForm.r_email.value;
    if(inputValue == null || inputValue == "")
    {
        message = message + "- Email Address\n";
        allFieldsValid = false;
    }
    inputValue = theForm.r_company.value;
    if(inputValue == null || inputValue == "")
    {
        message = message + "- Company Name\n";
        allFieldsValid = false;
    }
    inputValue = theForm.r_phone.value;
    if(inputValue == null || inputValue == "")
    {
        message = message + "- Phone #";
        allFieldsValid = false;
    }
    
    if(!allFieldsValid)
    {
        alert(message);
        return false;
    }

    theForm.submit();
    return true;
}