var CWTV = CWTV || {};

CWTV.Site = {};
CWTV.Site.LOGIN_MODE_CW			= 'cw';
CWTV.Site.LOGIN_MODE_SOCIAL		= 'social';
CWTV.Site.ua = {};
CWTV.Site.prefs = {};
CWTV.Site.ua.is_android = (navigator.userAgent.match(/android/i) != null);
CWTV.Site.ua.is_ipad = (m == 'ipad' || (navigator.userAgent.match(/ipad/i) != null) || (navigator.userAgent.match(/iphone/i) != null));

CWTV.Site.setMobilePreference = function(value, redirect_type)
{
	SetCWCookie2('mobile_preference', value );
	
	CWTV.Site.doRedirect( redirect_type );
}

CWTV.Site.getMobilePreference = function( do_redirect )
{
	// load mobile prefs
	CWTV.Site.prefs.mobile_preference = gup('mobile_preference');
	if ( CWTV.Site.prefs.mobile_preference == null || CWTV.Site.prefs.mobile_preference == '' )
		CWTV.Site.prefs.mobile_preference = GetCookie('mobile_preference');
	
	if ( CWTV.Site.prefs.mobile_preference == 'standard' || CWTV.Site.prefs.mobile_preference == 'mobile' ) {
		var redirect_type = (do_redirect && CWTV.Site.prefs.mobile_preference == 'mobile') ? 'mobile_site' : false;
		CWTV.Site.setMobilePreference( CWTV.Site.prefs.mobile_preference, redirect_type );
	}
	else
		CWTV.Site.prefs.mobile_preference = '';
	
	return CWTV.Site.prefs.mobile_preference;
}

CWTV.Site.doRedirect = function( redirect_type )
{
	if ( redirect_type && CWTV.Site.ua.is_android ) {
		switch (redirect_type)
		{
			case 'mobile_site':
				var current_uri = document.location.href
				document.location.href = "http://m.cwtv.com/?source=" + escape(current_uri);
				break;
			case 'full_episodes':
				document.location.href = "/cw-video/";
				break;
		}
	}
}

// check cookie and handle redirects
CWTV.Site.getMobilePreference( true );

function el(id) {
  if (document.getElementById) {
    return document.getElementById(id);
  } else if (window[id]) {
    return window[id];
  }
  return null;
}

function SetCWCookie(name, value) {
  document.cookie = name + "=" + value + ";path=/;domain=.cwtv.com";
}

function SetCWCookie2(name, value) {
    document.cookie = name + "=" + value + ";expires=Sun, 1 Jan 2018 12:00:00 UTC;path=/;domain=.cwtv.com";
}

function DeleteCWCookie(name, path) {
  SetCWCookie(name,"", -1, path);
}

function GetCookie(name) {
	var search = name + "=";
	var cookieString = document.cookie;	
	var result = null;
	if (cookieString.length > 0) {
		offset = cookieString.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookieString.indexOf(";", offset)
			if (end == -1) {
				end = cookieString.length
			}
			result = unescape(cookieString.substring(offset, end));
		}
	}
	return result;
}

function SetLoginPanel( ) {
	var li = el('login');
	var ui = el('signed-in');

	var username = GetCookie('cwsn');
	var userdata = GetCookie('cwud');
		
	if ( userdata != null && userdata != '' && username != null && username != '' ) {
		var data_vals = userdata.split(",");
				
		var uitpl = el('signed-in-panel');
		var panelHTML = uitpl.innerHTML
		var panel_style = data_vals[0];
		
		panelHTML= panelHTML.replace(/\+/gi," ");
		panelHTML= panelHTML.replace(/-0-/gi,username);	
		panelHTML= panelHTML.replace(/-2-/gi,data_vals[2]);
		panelHTML= panelHTML.replace(/-3-/gi,data_vals[3]);
		panelHTML= panelHTML.replace(/-4-/gi,data_vals[4]);
		
		uitpl.innerHTML = panelHTML;
		uitpl.className = 'login-style-' + panel_style;
		
		var uiimg = el('loggedin-img');
		uiimg.src = data_vals[1];
		
		if ( li )
			li.style.display = 'none';
		if ( ui )
			ui.style.display = '';
	}
	else {
		if ( ui )
			ui.style.display = 'none';
		if ( li )
			li.style.display = '';
	}
}

function SetLoginPanelKA( showkey ) {
	var li = el('login');
	var ui = el('signed-in');

	var username = GetCookie('cwsn');
	var userdata = GetCookie('cwud');
	var cwka = GetCookie('cwka-'+showkey);
	
	if ( showkey != null && showkey != '' && cwka == showkey
	        && userdata != null && userdata != '' && username != null && username != '' ) {
		var data_vals = userdata.split(",");
				
		var uitpl = el('signed-in-panel');
		var panelHTML = uitpl.innerHTML
		var panel_style = data_vals[0];
		
		panelHTML= panelHTML.replace(/\+/gi," ");
		panelHTML= panelHTML.replace(/-0-/gi,username);	
		panelHTML= panelHTML.replace(/-2-/gi,data_vals[2]);
		panelHTML= panelHTML.replace(/-3-/gi,data_vals[3]);
		panelHTML= panelHTML.replace(/-4-/gi,data_vals[4]);
		
		uitpl.innerHTML = panelHTML;
		uitpl.className = 'login-style-' + panel_style;
		
		var uiimg = el('loggedin-img');
		uiimg.src = data_vals[1];
	    
		li.style.display = 'none';
		ui.style.display = '';
	}
	else {
		ui.style.display = 'none';
		li.style.display = '';
	}
}

function addInputSubmitEvent(form, input) {
	input.onkeydown = function(e) {
		e = e || window.event;
		if (e.keyCode == 13) {
			if ( form.signinbtn )
				form.signinbtn.click();
			else
				form.click();
			return false;
		}
	};
}

function CheckSignInError( ) {
	var usererr = GetCookie('cwuerr');
	if ( usererr != null && usererr != '' ) {
		DeleteCWCookie('cwuerr', '/');
		usererr = usererr.replace(/\+/gi," ");
		alert( usererr );
	}
	
	// So IE can submit from keypress
	var f = el('signinform');
	if ( f ) {
		var inputs = f.getElementsByTagName('input');
		for (var i=0;i < inputs.length;i++)
			addInputSubmitEvent(f, inputs[i]);
    }
}

function OpenUserWin( command ) {
	var newwin = window.open( "/user/"+command, 'cwtvuser','width=650,height=664,status=yes,scrollbars=yes,resizable=no,location=no,toolbar=no');
	if (newwin) newwin.focus();
}

function OpenUserWin2( command ) {
	var newwin = window.open( "http://www.cwtv.com/user/"+command, 'cwtvuser','width=650,height=664,status=yes,scrollbars=yes,resizable=no,location=no,toolbar=no');
	if (newwin) newwin.focus();
}

function OpenPopupWin1(url,title,w,h) {
	var newwin = window.open( url,title,'width='+w+',height='+h+',status=yes,scrollbars=yes,resizable=no,location=no,toolbar=no');
	if (newwin) newwin.focus();
}

function OpenPopupWin2(url,title,w,h) {
	var newwin = window.open( url,title,'width='+w+',height='+h+',status=yes,scrollbars=yes,resizable=yes,location=no,toolbar=no');
	if (newwin) newwin.focus();
}

function resizeRegWin(newWidth,newHeight) {
	if (document.layers)
	{
		tmp1 = parent.outerWidth - parent.innerWidth;
		tmp2 = parent.outerHeight - parent.innerHeight;
		newWidth -= tmp1;
		newHeight -= tmp2;
	}
	parent.window.resizeTo(newWidth,newHeight);	
}

function SetURLParams(url, params){
    var q = url.indexOf('?');
    if (q != -1){
        url = url.substr(0, q);
    }
    var pairs = [];
    for (var i in (params || {})) {
        pairs.push(encodeURIComponent(i) + '=' + encodeURIComponent(params[i]));
    }
    if (pairs.length === 0) { // the caller is just clearing the URL
        return url;
    }
    return url + '?' + pairs.join('&');
}

function VideoCookieCheck() {
    if(document.cookie.indexOf('videovalid') == -1) {
        if(document.cookie.indexOf('nosoup') != -1) {
            return false;
        }
        else {
            url = document.location.href;
            url = SetURLParams('http://gksrv.cwtv.com/cwgeo', {'redir':url});
            document.location.href = url;
        }
    }
    return true;
}

function validEmail( text ) {			
	if ( text == '' )
		return false;
	
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if( reg.test(text) == false )
		return false;
	var illegalChars=/[\(\)\<\>\,\;\:\\\/\"\[\]]/;
	if (text.match(illegalChars))
		return false;
	return true;
}

function gup( name, urlSearch ) {
    if ( urlSearch == null )
        urlSearch = window.location.search;
        
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    
    var results = regex.exec( urlSearch );
    if( results == null )
        return null;
    else
        return results[1];
}

function share_cwlink(type,page_url) {
	if ( type == 'twit' || type == 'fb') {
		var page_title = window.document.title;
		opensharewindow("/cw-video/share-link?u="+escape(page_url)+"&t="+escape(page_title)+"&k="+type, type);
	}
}

function share_cwlink2(type,page_url,page_title,msg) {
	if ( type == 'twit' || type == 'fb') {
		if ( page_title == '' )
			page_title = window.document.title;
		opensharewindow("/cw-video/share-link?u="+escape(page_url)+"&t="+escape(page_title)+"&m="+escape(msg)+"&k="+type, type);
	}
}

function opensharewindow(url,type) {
	var newwin = window.open(url,"sharelink"+type,
			"width=1000,height=800,location=yes,menubar=yes,status=yes,toolbar=yes,scrollbars=yes,resizable=yes");
	if (newwin) newwin.focus();
}

function updateCWLoginStatus( ) {
	var cw_user_fb_uid = GetCookie('cwfb');
	var cw_user_fb_un = GetCookie('cwfbun');
	if ( cw_user_fb_uid > 0 && cw_user_fb_un != null )
	{		
		$('#fb-un').html( unescape(cw_user_fb_un.replace(/\+/g," ")) );
		$('#fb-url').attr('href', 'http://www.facebook.com/profile.php?id='+cw_user_fb_uid);
		
		$('#cw-user-loggedout').hide();
		$('#cw-user-fbloggedin').show();
	}
	else
	{
		var username = GetCookie('cwsn');
		var userdata = GetCookie('cwud');
		
		if ( userdata != null && userdata != '' && username != null && username != '' )
		{
			$('#cw-un').html(username);
		
			$('#cw-user-loggedout').hide();
			$('#cw-user-loggedin').show();
		}
		else
		{
			$('#cw-user-fbloggedin').hide();
			$('#cw-user-loggedin').hide();
			$('#cw-user-loggedout').show();
		}
	}
}
	
function open_centered_window(url,title,width,height) {
	var w = $(window).width();
	var h = $(window).height();
	var top = window.screenTop != undefined ? window.screenTop : window.screenY;
	var left = window.screenLeft != undefined ? window.screenLeft : window.screenX;
	var leftPos = left + Math.floor((w - width) / 2);
	var topPos = top + Math.floor((h - height) / 2);
	
	var windowFeatures = 'width=' + width +  ',height=' + height + ',top=' + topPos +  ',left=' + leftPos + ',location=no,menubar=no,status=yes,toolbar=no,scrollbars=yes,resizable=no';
	newwin = window.open(url,title,windowFeatures);
	if (newwin)
		newwin.focus();
}
	
function open_cw_login(mode) {
	if ( CWTV.LoginMode == CWTV.Site.LOGIN_MODE_SOCIAL )
		open_centered_window("/community-b7?m=social","community",800,520);
	else
		open_centered_window("/community-b7","community",800,520);
}
	
function open_cw_logout() {
	open_centered_window("/community-b7/logout","community",800,520);
}

function open_cw_login_ext(mode) {
	open_centered_window("http://www.cwtv.com/community-b7","community",800,520);
}
	
function open_cw_logout_ext() {
	open_centered_window("http://www.cwtv.com/community-b7/logout","community",800,520);
}


$(function() {
	
	if ( 0 ) {
		$('.android_btn').click(function() {
			var id = $(this).attr('id');
			
			$.modal.close();
			
			if ( id == 'android_standard' ) {
				CWTV.Site.setMobilePreference( 'standard', false );
			}
			else if ( id == 'android_mobile' ) {
				CWTV.Site.setMobilePreference( 'mobile', 'mobile_site' );
			}
			else if ( id == 'android_fullepisodes' ) {
				CWTV.Site.setMobilePreference( 'standard', 'full_episodes' );
			}
			
			return false;
		});
				
		if ( CWTV.Site.ua.is_android ) {
			if ( CWTV.Site.prefs.mobile_preference == 'standard' ) {
				// stay on site
			} else if ( CWTV.Site.prefs.mobile_preference == 'mobile' ) {
				// prefers mobile
			} else {
				// no pref set
				$('#android_popup').modal({focus:false,opacity:80});
			}
		}
	}
});	


