var OTT = {};
var jQ = jQuery;
OTT.UI = {};
OTT.CACHE = {prices:{}, session:{request:{fields:{}}}};

OTT.UI.Overlay = {
			
			elems: 	{
						
					},
			
			html: {
					transparent_bg:'<div class="transparent_overlay" class="hidden"></div>',
					overlay:'<div class="overlay_content_wrap" class="hidden"><div class="overlay_positioner"><div class="overlay_outer"></div></div></div>',
					content:'<div class="overlay"></div>'
				},
			
			selector: {
				body:'body',
				overlay_parent:'.overlay_outer',
				overlay:'.overlay'
			},
			
			prepare: function() {
				
				this.elems.trans_back = this.elems.trans_back || jQ(this.html.transparent_bg).appendTo('body');
				this.elems.overlay_wrap = this.elems.overlay_wrap || jQ(this.html.overlay).appendTo('body');
				
				this.elems.overlay = this.elems.overlay_wrap.find(this.selector.overlay_parent);
				
				var bodyHeight=jQ(this.selector.body).height();
				var contentHeight = OTT.UI.get_content_height();
				
				this.elems.trans_back.removeClass('hidden').
							height(bodyHeight>contentHeight?bodyHeight:contentHeight).
							fadeTo(100,0.5);
							
				//if that's IE six we need to hide selects as well
				if (jQ.browser.msie && parseInt(jQ.browser.version,10)<7) {
					
					jQ('select').css('visibility','hidden');
					
				}
			
			},
			
			hide: function(callback) {
				
				var self = this;
				var all_elems = self.elems.trans_back.add(OTT.UI.Overlay.elems.overlay_wrap);
				
				jQ(all_elems).fadeTo('fast',0, function() {
	
					jQ(all_elems).addClass('hidden');
				
					if (jQ.browser.msie && parseInt(jQ.browser.version,10)<7) {
				
						jQ('select').css('visibility','visible');
				
					}
				
				});
				
				self.elems.content.unbind_events();
				
				if (callback) {
						setTimeout(function() {callback.call(self.elems.overlay)},1);
				}
		
			},
			
			show: function(content, callback) {
				
				var self = this;
				
				//this function will be massively different for IE6
				//so branching is used to create once not to bother
				//good browsers with this trivia
				var unveil_and_position = (function() {
						
					
							return function() {
								self.elems.overlay_wrap.removeClass('hidden').fadeTo(100,1, function() {
								if (jQ.browser.msie && parseInt(jQ.browser.version,10)<7) {
								//IE 6 keeps forgetting what 100% is when the overlay is shown
										jQ('.overlay_content_wrap').height(document.documentElement.clientHeight);
									}
								}
								)
							}
						
				})();
				
				if (content) {
				
					self.prepare();
					self.elems.content = content;

					unveil_and_position();
				
					self.elems.overlay.html(content.content);
					
					content.bind_events();
					
					if (callback) {
						setTimeout(function() {callback.call(self.elems.overlay)},1);
					}
				
				}
								
			}


}

OTT.UI.Overlay_content = 	function(content, events) {
								
								this.content = content || '';
								
								this.events = events || [];
								
								this.events.push(
															{
																selector:'.hide_overlay',
																event:'click',
																fn:function() {OTT.UI.Overlay.hide();return false}
															}
												);
								
								this.bind_events = function() {
									
									for (var e=0;e<this.events.length;e++) {
										var event = this.events[e];
										event.event = event.event || 'click';
										jQ(event.selector).bind(event.event, event.fn);
									}
									
								};
								
								this.unbind_events = function() {
									
									for (var e=0;e<this.events.length;e++) {
										var event = this.events[e];
										event.event = event.event || 'click';
										jQ(event.selector).unbind(event.event);
									}
									
								};
								
								

							};

//creates dropdown
OTT.UI.populate_select =        function(source,value,label,preselected) {

								//value and label are in relation to source

								r = [];

								for (var o=0;o<source.length;o++) {

										r.push('<option '+
														(preselected === o ? 'selected="selected "':'')+
														(value?'value="'+source[o][value]:'')+'"'+
														'>'+
														label.call(source[o])+
														'</option>');
								};

								return r.join("\n");

                            };

OTT.UI.get_content_height = function () {

	return jQ('#sur_head').height()+jQ('#sur_content').height()+jQ('#sur_foot').height();

};
							
OTT.Domain_search = function(API, UI, CONF) {
	
	var self = this;
	this.API = new API(self);
	this.UI = new UI(self);
	this.CONF = new CONF(self)
	
	$(self).bind('domain_results_ready', function(e,data_obj) {
		self.present_results(data_obj);
	});
	
	$(self).bind('domain_call_unsuccessful', function(e,data_obj) {
	});
	
	$(self).bind('domain_chosen', function(e,data_obj) {
		var r = new OTT.Request(OTT.CACHE.session.request.action, 'post', data_obj);
		r.send();
	});
	
	$(self).bind('domain_search_initiated', function(e,data_obj) {
		self.UI.display_search_progress();
		self.get_results(data_obj);
	});
	
	this.get_results = function(data_obj) {
		
		self.get_more_results(data_obj);
		
	}
	
	this.get_more_results = function(data_obj) {
	
		if (this.CACHE.extensions_index && this.CACHE.extensions_index < this.CONF.extensions.length) {
			this.CACHE.extensions_index++;
		}
		
		this.CACHE.current_extensions = this.CONF.extensions[this.CACHE.extensions_index];
		
		this.API.check_domain_availability(data_obj);
			
	}
	
	this.present_results = function(data_obj) {
			
		this.UI.present_results(data_obj);
	}
		
	this.init = function() {
		this.UI.capture_domain_search();
	}
	//all should be static
	this.CACHE = {
		extensions_index:0,
		current_extensions:[]
	};

};

OTT.Request = function(action, method, fields) {
	
	var form_html = ['<form action="'+(action||'')+'" method="'+(method||'post')+'">'];
	
	for (var i=0; i<fields.length; i++) {
		
		form_html.push('<input type="'+(fields[i].type||'hidden')+'" name="'+fields[i].name+'" value="'+fields[i].value+'" />');
			
	}
	
	form_html.push('</form>');
	
	var $form = jQ(form_html.join(''));
	
	this.send = function() {
		jQ('body').append($form);
		$form.submit();
	}
	
	var destroy = function() {
		$form.remove();
	}
};

F= {};


F.create_cookie =		function(name,value,days) {
									if (days) {
										var date = new Date();
										date.setTime(date.getTime()+(days*24*60*60*1000));
										var expires = "; expires="+date.toGMTString();
									}
									else {
										var expires = "";
									}
									document.cookie = name+"="+value+expires+"; path=/";
						};

F.read_cookie = 		function (name) {
									var nameEQ = name + "=";
									var ca = document.cookie.split(';');
									for (var i=0; i < ca.length; i++) {
										var c = ca[i];
										while (c.charAt(0)==' ') {
											c = c.substring(1,c.length);
										}
										if (c.indexOf(nameEQ) == 0) {
											return c.substring(nameEQ.length,c.length);
										}
									}
									return null;
						};

F.erase_cookie =		function(name) {
									DAC.utils.createCookie(name,"",-1);
						};
								
F.get_hostname_extension = function(domain_input, extensions) {
	
	var hostname =	domain_input.toLowerCase(),
		extension =	'';
	
	if(domain_input.indexOf('www')===0){
		//get rid of www and assign new value to var
		hostname = domain_input.replace('www.', '');		
	};

	//roughly sanitize
	hostname = hostname.replace(/[^\w-.]/g,'');
	
	//correct order of validating domain
	//1. sanitize roughly
	//this will make sure that space or weird characters in final position
	//don't interfere with extension recognision
	//like www.-sdas-12()&.com%
	//2. identify and chop off extension
	//3. sanitize thoroughly the remaining hostname
	
		for (var i=0;i<extensions.length;i++) {
			
			var ext = extensions[i];
			//if extension can be found in domain input
			//and found extension is in the last position
			//and found extension is the longest found extension
			if (hostname.lastIndexOf(ext) > 0 && hostname.lastIndexOf(ext) + ext.length === hostname.length && ext.length>extension.length) {
					extension = ext;
					var ext_index = hostname.lastIndexOf(ext);
			}
		}
	
	
	
	if (extension) {
		hostname = hostname.substring(0,ext_index);
	}
	
	return {
				hostname:hostname
				,
				extension:extension
		
			};
			
};


F.cleanup_hostname = function(hostname, extension) {
	
	//3-63 characters, alphanumeric+'-'
	var re=/[^\w-]/g;

	//add dot for name
	if (extension==='.name') {var re=/[^\w\.{1}-]/g}

	var re2=/(^-)-*/;
	var re3=/-*(-$)/;
	var re4=/_/g;


	hostname=hostname.replace(re,'').replace(re2,'').replace(re3,'').replace(re4, '').toLowerCase();

	hostname=hostname.substr(0,63);

	//change it to an empty string if it's undefined
	hostname=hostname||'';

	return hostname;

};

F.to_price =						function (num_amount, str_currency) {
										
										//returns nicely formatted price
										//with 2 decimal places
										
										var price, symbol;
										
										if (typeof num_amount === 'number') {
											
											switch (str_currency) {
											
													case 'GBP':
													symbol='&pound;';
													break;
													
													case 'USD':
													symbol='&#36;';
													break;
													
													default:
													symbol='&pound;';
													break;
											
											}
											
											return symbol+num_amount.toFixed(2);
										
										}
										
									
									};

F.getScroll =						function() {
	
										var scrOfX = 0, scrOfY = 0;
	
										if( typeof( window.pageYOffset ) == 'number' ) {
										//Mozilla compliant
											scrOfY = window.pageYOffset;
											scrOfX = window.pageXOffset;
										}
										
										else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
											//DOM compliant
											scrOfY = document.body.scrollTop;
											scrOfX = document.body.scrollLeft;
										}
										
										else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
											//IE6 standards compliant mode
											scrOfY = document.documentElement.scrollTop;
											scrOfX = document.documentElement.scrollLeft;
										}
										
										return [ scrOfX, scrOfY ];
			
									};

F.toJSONString = 			function(obj) {
			
									var isArray=function(_obj) {
									return _obj instanceof Array;
									};
									
									var isObject=function(_obj) {
									return (_obj instanceof Object) && !(_obj instanceof Array);
									};
									
									var isString=function(_obj) {
									return !!(typeof _obj =='string');
									};
									
									var isNumber=function(_obj) {
									return !!(typeof _obj =='number');
									};
									
									var qt = function(str) {
									return "\""+str+"\"";
									};
											if (isArray(obj)) {
													var output=[];
													for (var i=0,l=obj.length;i<l;i++) {
													output.push(arguments.callee(obj[i]));
													}
													return '['+output.join(', ')+']';
											}
									
											if (isObject(obj)) {
													var output=[];
													for (var i in obj) {
													output.push(qt(i)+":"+arguments.callee(obj[i]));
													}
													return '{'+output.join(', ')+'}';
											}
									
											if (isString(obj)) {
													return qt(obj);
											}
									
											if (isNumber(obj)) {
													return obj;
											}
									
								};

F.toObject = 					function(str_JSON) {
									if (str_JSON.indexOf('{')==0 && str_JSON.lastIndexOf('}')==str_JSON.length-1) {
										return eval('(' + str_JSON + ')');
									}
									else {
										return null;
									}
								};



/*=======================================*/

jQ(document).ready(function() {

    jQ('div.thumbnailPod a').click(function() {
        var thisHref = jQ(this).attr('href');
        var overlay_html = [
            '<div class="overlay" id="video_overlay">',
                '<a href="#close" id="close_overlay" class="hide_overlay">hide</a>',
                '<div id="media">',
                    '<iframe src ="' + thisHref + '" width="800" height="540" frameborder="0" allowtransparency="true"></iframe>',
                '</div>',
            '</div>' 
		    ].join("\n");
    
        var overlay_content = new OTT.UI.Overlay_content(
	        overlay_html,
	        [
                {
                    selector:'.hide_overlay',
                        fn:function() {
                            OTT.UI.Overlay.hide(function() {
                                OTT.UI.Overlay.elems.overlay.find('.overlay').empty();
                            });
                            return false;
                        }
                }
            ] 
        );

        OTT.UI.Overlay.show(overlay_content);
	    
	    jQuery.ajax({
	        url: "SpVideos.aspx",
	        data: "accesscount=" + thisHref,
            type: "POST",
            success: function(response){
                            //callback pentru procesarea raspunsului primit
                            }
            });
	    
	    return false;
	});


	

});
