/**
 * DOM Utilies Object for handling basic DOM actions
 * @author					Dave Shepard
 * @version					1.0
 * @required libraries:		Prototype 1.6 or later
 * 
 * Usage:
 *     DOMUtilities.init();
 * 
 * Can be initialized via the init(); method to apply to entire <body> or
 * a scope can be passed to limit the initialization to the child elements
 * of a particular element. Individual methods can als be called and passed
 * a scope.
 */
var DOMUtilities = {
	targetBlank: function(locality){
		// XHTML 1.0 Strict work around for external links
		$$(locality+' a[rel*="external"]').each(function(e){
			e.writeAttribute("target","_blank");
		});
	},
	inputAutoClear: function(locality){
		// Automatic text clear
		$$(locality+' input.clearField').each(function(e){
			e.observe('focus',function(){
				this.value = "";
			}).observe('blur',function(){
				if(this.value == "") {
					this.value = this.defaultValue;
				}
			});
		});		
	},
	imgRollover: function(locality){
		// Image roll-over setup
		$$(locality+' img.rollOver, '+locality+' input[type="image"].rollOver').each(function(e){
			e.observe('mouseover',function(){
				if (this.src.indexOf("_i.") != -1) {
					this.src = this.src.replace("_i.", "_o.");
				}
			}).observe('mouseout',function(){
				if (this.src.indexOf("_o.") != -1) {
					this.src = this.src.replace("_o.", "_i.");
				}
				if(this.src.indexOf("_a.")) {
					this.src = this.src.replace("_a.","_i.");
				}
			})
			if(e.match("input")) {
				e.observe('mousedown',function(){
					this.src = this.src.replace("_o.","_a.");
				}).observe('mouseup',function(){
					this.src = this.src.replace("_a.","_i.");
				});
			}
		});
	},
	init: function(locality){
		if(locality == null) {
			locality = "body";
		}
		this.targetBlank(locality);
		this.inputAutoClear(locality);
		this.imgRollover(locality);
	}
}

/**
 * Cufon font initializer
 * @author					Dave Shepard
 * @version					0.2
 * @required libraries:		Prototype 1.6 or later, Cufon 
 * 
 * Usage:
 *     $(document).observe("dom:loaded",function(){
 *         CufonFonts.init();
 *     });
 * 
 * An initialization script for Simo Kinnunen's Cufon font replacer available 
 * at: http://wiki.github.com/sorccu/cufon. This is an independent
 * script from Cufon and is unsupported by Sorccu.
 * 
 * Fill the CufonInitializer.fonts array with objects containing the font CSS
 * name and the elements to apply the font to in the CufonInitializer.fonts.elements
 * array. Elements to apply the font to will take any CSS font reference method
 * supported by Prototype.
 */
var CufonFonts = {
	fonts: [
		{
			name: 'Omnes',
			elements: [
				'#my_shorthand_header_container .myShorthandHeaderContainer h4>span.title',
				'#session_welcome',
				'#browse_apps_filter_container h2',
				'.grayBlock h4.title',
				'.whiteBlock ht4.title',
				'#sideload_tooltip span.subtitle',
				'#whyemail_tooltip span.subtitle',
				'#howdoiknow_tooltip span.subtitle',
				'#whatsthis_tooltip span.subtitle',
				'#remove_application_contents h3.title',
				'#remove_application_instructions ol li',
				'#content_public h1',
				'#content_public h3',
				'#content_public h4',
				'#not_available_contents h2',
				'#register_col_left h1',
				'#register_col_right h3',
				'#register_col_right h4',
				'#partners_feature p',
				'#home_header h1',
				'#welcome_content'
			]
		},
		{
			name: 'Omnes Semibold',
			elements: [
				'#sideload_tooltip span.title',
				'#howdoiknow_tooltip span.title',
				'#whyemail_tooltip span.title',
				'#whatsthis_tooltip span.title',
				'#remove_application_contents h4.subtitle',
				'#home_testimonial h4',
				'#content_public.content_home #col_right h5 .title',
				'.post_title h2'
			]
		},
		{
			name: 'Omnes',
			elements: [
				'#nav_primary>li>a',
				'#nav_secondary>li>a',
				'#free_beta'
			],
			options: {
				textShadow : '#e2e2e2 1px 1px'
			}
		}
	],
	init: function(){
		this.fonts.each(function(f){
			var existingElements = [];
			f.elements.each(function(cfe){
				if($$(cfe).length > 0) existingElements.push(cfe);
			});
			var cufonOptions = {
				fontFamily : f.name
			}
			if(!Object.isUndefined(f.options)){
				var optionKeys = Object.keys(f.options);
				var optionVals = Object.values(f.options);
				for(i=0 ; i < optionKeys.length ; i++){
					cufonOptions[optionKeys[i]] = optionVals[i];
				}
			}
			Cufon.replace(existingElements.join(","),cufonOptions);
		});
	}
}

/**
 * Pagination tracking "lite"
 * @author					Dave Shepard
 * @version					0.2l
 * 
 * For use with Scroller Object to update pagination for "My Apps" scroller
 */
var MyAppPagination = {
	animating: false,
	parentID: "",
	pages: 1,
	current: 1,
	updatePage: function(){
		 if($(this.parentID).childElements().length > 0)
	    {
		    var current_showing_count = $(this.parentID).childElements()[this.current-1].childElements().length;
		    var start_count = this.current == 1 ? 1 : ((this.current - 1) * 8) + 1;
		    var end_count = start_count + current_showing_count - 1;
		    
	    }
	    else
	    {
	        var current_showing_count = 0;
	        var start_count = 0;
	        var end_count = 0;
	    }
	    $('my_apps_scroller_showing').update(start_count+"-"+end_count);
	},
	updateTotal: function(){
		$('my_apps_scroller_total').update($$('#'+this.parentID+' .myAppThumbnail').length);
	},
	init: function(parent_id){
		this.parentID = parent_id;								// Set the passed in ID as the parentID value
		this.pages = $(parent_id).childElements().length;		// Set the number of child elements
		this.updatePage();
		this.updateTotal();
	}
}

/**
 * Screenshot pagination tracking
 * @author					Dave Shepard
 * @version					0.1
 * 
 * Meant for use with Scroller Object to update indicator for screenshot
 * currently being viewed on the App Detail page
 */
var ScreenShotPagination = {
	animating: false,
	scrollerObj: null,
	parentID: "",
	pagesID: "",
	pages: 1,
	current: 1,
	updateCurrent: function(){
		$$('#' + this.pagesID + ' a').each(function(e,ind){
			if(ind + 1 == this.current)
				e.addClassName('active');
			else
				e.removeClassName('active');
		},this);
	},
	assign: function(){
		$$('#' + this.pagesID + ' a').each(function(e,ind){
			var self = this;
			e.observe('click',function(event){
				event.stop();
				self.current = ind + 1;
				self.scrollerObj.gotoPage(ind,{
					callBack: function(){
						self.updateCurrent();
					}
				});
			});
		},this);
	},
	init: function(scrollerObj, pages_id){
	    this.current = 1;
		this.scrollerObj = scrollerObj;
		this.parentID = scrollerObj.scroller_id;				// Set the passed in ID as the parentID value
		this.pagesID = pages_id;
		this.pages = $(this.parentID).childElements().length;	// Set the number of child elements
		
		$(this.pagesID).setStyle({
			marginLeft: 0 - (($(this.pagesID).down().getDimensions().width * this.pages) / 2) + "px"
		})
		
		this.assign();
		this.updateCurrent();
	}
}

var AppPreview = {
	id: "app_preview",
	classes: {
		thumbnail: "app_thumbnail",
		block: "app_block",
		meta: "app_preview_meta",
		content: "app_preview_content",
		left: "boxLeft",
		right: "boxRight"
	},
	
	show: function(element,side){
		
		var content = $(element).up('.' + this.classes.block).down('.' + this.classes.content).innerHTML;
		
		var newPosition = element.cumulativeOffset();
        var leftPos = 63;
        if(side == this.classes.right)
        {
            leftPos = -7;
        }
		$(this.id).addClassName(side)
			.removeClassName(side == this.classes.left ? this.classes.right : this.classes.left)
			.update(content)
			.show()
			.setStyle({
				left: newPosition.left + leftPos + "px",
				top: newPosition.top + 40 + "px"
			});
	},
	
	assign: function(){
	
		$$('.' + this.classes.thumbnail).each(function(e,ind){
			e.addClassName((ind % 5 > 2) ? this.classes.right : this.classes.left).observe('mouseenter',function(event){
				AppPreview.show(e,(e.hasClassName(AppPreview.classes.right) ? AppPreview.classes.right : AppPreview.classes.left));
			});
		},this);
		$(this.id).addClassName(this.classes.left).observe('mouseleave',function(event){
			$(this).hide();
		});	
	},
	
	init: function(){
	
		this.assign();
	}
}

var AppRotator = {
	id: 'apps_rotator',
	childClass: 'appName',
	elements: [],
	delay: 3,
	
	crossFade: function(){
		var self = this;
		
		var next = this.current + 1;
		if(this.current == (this.elements.length - 1)){
			next = 0;
		}
		
		new Effect.Parallel([
				new Effect.Fade(this.elements[this.current], { sync: true }),
				new Effect.Appear(this.elements[next], {
					sync: true,
					afterFinish: function(){
						self.current = next;
						self.crossFade();
					}
				})
			],
			{
				duration: 1,
				delay: this.delay
			}
		);
	},
	
	initialize: function(){
		this.elements = $(this.id).select('.' + this.childClass);
		for(var i = 0; i < this.elements.length; i++){
			if(this.elements[i].visible()){
				this.current = i;
			}
		}
		
		this.crossFade();
	}
}

var AppRotator_Brazil = {
	id: 'apps_rotator_Brazil',
	childClass: 'appName',
	elements: [],
	delay: 3,
	
	crossFade: function(){
		var self = this;
		
		var next = this.current + 1;
		if(this.current == (this.elements.length - 1)){
			next = 0;
		}
		
		new Effect.Parallel([
				new Effect.Fade(this.elements[this.current], { sync: true }),
				new Effect.Appear(this.elements[next], {
					sync: true,
					afterFinish: function(){
						self.current = next;
						self.crossFade();
					}
				})
			],
			{
				duration: 1,
				delay: this.delay
			}
		);
	},
	
	initialize: function(){
		this.elements = $(this.id).select('.' + this.childClass);
		for(var i = 0; i < this.elements.length; i++){
			if(this.elements[i].visible()){
				this.current = i;
			}
		}
		
		this.crossFade();
	}
}


$(document).observe("dom:loaded",function(){
	DOMUtilities.init();
	CufonFonts.init();
	
	if($('app_preview')){
		AppPreview.init();
	}

	if ($('my_apps_scroller_list')) {
		new Scroller('my_apps_scroller_list', 'btn_my-apps-scroller_next', 'btn_my-apps-scroller_prev', {
			extraOffset: 10
		}, {
			previous: {
				callBack: function(){
					MyAppPagination.current--;
					MyAppPagination.updatePage();
				}
			},
			next: {
				callBack: function(){
					MyAppPagination.current++;
					MyAppPagination.updatePage();
				}
			}
		});
		MyAppPagination.init('my_apps_scroller_list');
	}
	
	if ($('featured_apps_scroller_list')) {
		new Scroller('featured_apps_scroller_list', 'btn_featured-apps-scroller_next', 'btn_featured-apps-scroller_prev',{ scrolling: true });
	}
	
	if ($('app_detail_screenshots_block')) {
		var screenshotScroller = new Scroller('app_detail_screenshots_block', 'btn_next-screenshot', 'btn_previous-screenshot', {
		extraOffset: 0
		}, {			
			previous: {
				callBack: function(){
					ScreenShotPagination.current--;
					ScreenShotPagination.updateCurrent();
				}
			},
			next: {
				callBack: function(){
					ScreenShotPagination.current++;
					ScreenShotPagination.updateCurrent();
				}
			}
		});
		ScreenShotPagination.init(screenshotScroller,'app_detail_screenshots_pages');
	}
	
	
	
	// Code for retaining the A-Z and Category divs starts here
	
	if(document.location.href.match('alpha'))
	{
	    if( $('my_apps_scroller_elements') == null || $('my_apps_scroller_elements') != null)
	    {
	    $$('#nav_browse_tabs li a').each(function(e)
	    {
		    if(e.href.include('#')) 
		    {
				    //$$('#nav_browse_tabs li a').invoke('removeClassName','active');
    				
				    var section = "alphabetical";
				    var newHeight = 0;
    				
				    if($('subfilter_option_alphabetical')) 
				    {
					    $$('#browse_app_subfilter_options .subfilterOptions').each(function(e)
					    {
						    if(e.id.split('_').last() == "alphabetical") 
						    {
							    e.addClassName('active');
							    new Effect.Appear(e,
							    {
								    duration: 0.5
							    });
						    } 
						    else 
						    {
							    e.removeClassName('active');
							    new Effect.Fade(e,
							    {
								    duration: 0.5
							    });
						    }
					    });
					    newHeight = $('subfilter_option_alphabetical').getDimensions().height;
				    }
				    new Effect.Morph('browse_app_subfilter_options',
				    {
					    style: 'height: '+newHeight+'px',
					    duration: 0.5
				    });
		        }
	        });
	    }
	}
	else if(document.location.href.match('category'))
	{
	    if( $('my_apps_scroller_elements') == null || $('my_apps_scroller_elements') != null)
	    {
	    $$('#nav_browse_tabs li a').each(function(e)
	    {
		    if(e.href.include('#')) 
		    {
				    //$$('#nav_browse_tabs li a').invoke('removeClassName','active');
    				
				    var section = "category";
				    var newHeight = 0;
    				
				    if($('subfilter_option_category')) 
				    {
					    $$('#browse_app_subfilter_options .subfilterOptions').each(function(e)
					    {
						    if(e.id.split('_').last() == "category") 
						    {
							    e.addClassName('active');
							    new Effect.Appear(e,
							    {
								    duration: 0.5
							    });
						    } 
						    else 
						    {
							    e.removeClassName('active');
							    new Effect.Fade(e,
							    {
								    duration: 0.5
							    });
						    }
					    });
					    newHeight = $('subfilter_option_category').getDimensions().height;
				    }
				    new Effect.Morph('browse_app_subfilter_options',
				    {
					    style: 'height: '+newHeight+'px',
					    duration: 0.5
				    });
		        }
	        });
	    }
	}
	    
	// Code for retaining the A-Z and Category divs ends here
	
	
	
	if( $('my_apps_scroller_elements') == null || $('my_apps_scroller_elements') != null)
	{
	    $$('#nav_browse_tabs li a').each(function(e){
		    if(e.href.include('#')) {
			    e.observe('click',function(event){
				    Event.stop(event);
				    $$('#nav_browse_tabs li a').invoke('removeClassName','active');
				    e.addClassName('active');
    				
				    var section = e.href.substr(e.href.indexOf('#')+1);
				    var newHeight = 0;
    				
				    if($('subfilter_option_'+section)) {
					    $$('#browse_app_subfilter_options .subfilterOptions').each(function(e){
						    if(e.id.split('_').last() == section) {
							    e.addClassName('active');
							    new Effect.Appear(e,{
								    duration: 0.5
							    });
						    } else {
							    e.removeClassName('active');
							    new Effect.Fade(e,{
								    duration: 0.5
							    });
						    }
					    });
					    newHeight = $('subfilter_option_'+section).getDimensions().height;
				    }
				    new Effect.Morph('browse_app_subfilter_options',{
					    style: 'height: '+newHeight+'px',
					    duration: 0.5
				    });
			    }).onclick = function(){ return false; }
		    }
	    });
    	
	    if($('link_sideload_help')){
		    $('link_sideload_help').observe('mouseenter',function(event){
			    $('sideload_tooltip').show();
		    }).observe('mouseleave',function(event){
			    $('sideload_tooltip').hide();
		    }).onclick = function(){ return false; }
		    new Event.observe(document,'mousemove',function(event){
			    if(event.element() == $('link_sideload_help')){
				    $('sideload_tooltip').setStyle({
					    top: (event.pointerY() - $('sideload_tooltip').getDimensions().height - 3)+"px",
					    left: (event.pointerX() - $('sideload_tooltip').getDimensions().width + 30)+"px"
				    });
			    }
		    });
	    }
	}
	
	if($('link_howdoiknow'))
	{
		$('link_howdoiknow').observe('mouseenter',function(event){
			$('howdoiknow_tooltip').show();
		}).observe('mouseout',function(event){
			$('howdoiknow_tooltip').style.display = 'none';		
		}).onclick = function(){ return false; }
		new Event.observe(document,'mousemove',function(event){
			$('howdoiknow_tooltip').setStyle({
				top: (event.pointerY() - $('howdoiknow_tooltip').getDimensions().height - 3)+"px",
				left: (event.pointerX() - $('howdoiknow_tooltip').getDimensions().width + 45)+"px"
			});
		});
	}
	
	if($('link_whyemail'))
	{
		$('link_whyemail').observe('mouseenter',function(event){
			$('whyemail_tooltip').show();
		}).observe('mouseout',function(event){
			$('whyemail_tooltip').style.display = 'none';		
		}).onclick = function(){ return false; }
		new Event.observe(document,'mousemove',function(event){
			$('whyemail_tooltip').setStyle({
				top: (event.pointerY() - $('whyemail_tooltip').getDimensions().height - 3)+"px",
				left: (event.pointerX() - $('whyemail_tooltip').getDimensions().width + 45)+"px"
			});
		});
	}
	if($('link_whatsthis'))
	{
		$('link_whatsthis').observe('mouseenter',function(event){
			$('whatsthis_tooltip').show();
		}).observe('mouseout',function(event){
			$('whatsthis_tooltip').style.display = 'none';		
		}).onclick = function(){ return false; }
		new Event.observe(document,'mousemove',function(event){
			$('whatsthis_tooltip').setStyle({
				top: (event.pointerY() - $('whatsthis_tooltip').getDimensions().height - 3)+"px",
				left: (event.pointerX() - $('whatsthis_tooltip').getDimensions().width + 245)+"px"
			});
		});
	}
	
	if($$('#btn_remove_app_cancel, #btn_login_cancel, #btn_register_cancel, #link_Back, #btn_appfinder_cancel, #link_ok, #welcome_ok, #link_Success').length > 0){
		$$('#btn_remove_app_cancel, #btn_login_cancel, #btn_register_cancel, #link_Back, #btn_appfinder_cancel, #link_ok, #welcome_ok, #link_Success').each(function(e){
			e.observe('click',function(event){
				event.stop();
				Lightview.hide();
			}).onclick = function(){ return false; }
		});
	}
	
	if($('team_photo')){
		$$('#team_photo a.teamLink').each(function(e){
			e.observe('click',function(event){
				event.stop();
				var hash = e.href.substr(e.href.indexOf('#')+1);
				new Effect.ScrollTo(hash,{
					afterFinish: function(){
						document.location.hash = hash;
					}
				});
			}).onclick = function(){ return false; }
		});
	}
	
	if($('btn_tell-a-friend')){
		$$('#btn_tell-a-friend, #link_close_tell-a-friend, #btn_footer-tell-a-friend').each(function(e){
			e.observe('click',function(event){
				event.stop();
				var container = $('tell-a-friend_container');
				if(parseInt(container.getStyle('right')) < 0){
					// Open
					container.setStyle({zIndex: 100001});
					$('ctl00_TellFriend_txbTellYourEmail').focus();
					new Effect.Morph(container,{
						style: {
							right: "0px"
						},
						transition: Effect.Transitions.sinoidal,
						duration: 0.5
					})
				} else {
					// Close
					new Effect.Morph(container,{
						style: {
							right: 0 - parseInt(container.getStyle('width')) + "px"
						},
						transition: Effect.Transitions.sinoidal,
						duration: 0.5,
						afterFinish: function(){
							container.setStyle({zIndex: 99999});
							$('ctl00_TellFriend_tell_a_friend_form').focus();
						}
					})
				}
			}).onclick = function(){ return false; }
		});
		
	}
	
	
	if($('input_phone_number_1'))
	{	
        $('input_phone_number_1').observe('keyup',function(event)
        {	        
	        if(event.keyCode >= 48)
	        {
		        if(this.value.length == 3) 
		        {
			        $('input_phone_number_2').focus();				    
		        }
		    }		  
	    });
	    $('input_phone_number_2').observe('keyup',function(event)
	    {		    
	        if(event.keyCode >= 48)
	        {
		        if(this.value.length == 3)
		        {
		            $('input_phone_number_3').focus();
			    }	    
			}				   
	    });
	    $('input_phone_number_3').observe('keyup',function(event)
	    {
	        if(event.keyCode >= 48)
	        {
		        if(this.value.length == 4)
		        {			   				    
			        $('input_login_password').focus();				    
		        }
		    }
	    });	    
	}
	
	if($('apps_rotator')) {
		AppRotator.initialize();
	}
	
	if($('apps_rotator_Brazil')) {
		AppRotator_Brazil.initialize();
	}
});

document.observe('lightview:opened',function(){
	if($('input_phone_number_1')){
		$('input_phone_number_1').focus();
	}
});
