var isExtended = 0;
var myHTML = '';

// AJAX FUNCTIONS //      
function makeRequest(url, parameters, myfunc) {
    var http_request;
    
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
    }

    if (!http_request) {
            alert('AJAX - Giving up : Cannot create an XMLHTTP instance');
            return false;
    }    
        
    http_request.onreadystatechange = function(){                       
            if (http_request.readyState == 4) {                  
                    myfunc(http_request.responseText);                                               
            }  
    };           

    http_request.open('POST', url, true);
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http_request.setRequestHeader("Content-length", parameters.length);
    //http_request.setRequestHeader("Connection", "close");
    http_request.send(parameters);
      
}

$(document).ready(function() {
   var popOut = "#popout"; // Name of the popout container.
   var popBox = "#popoutbox"; // Name of the animated bit of the ad.
   var popWidth = $(popBox).width() + $("#cap").width(); // Width of the ad container.
   
   function openAd() {
      $(popOut).width(popWidth+"px");
      $(popBox).animate({marginLeft: "0"},1200)
      isExtended = 1;  
      document.getElementById('open').src = '/images/slide-button-active.gif';    
   }
   
   function closeAd() {
      $(popBox).animate({marginLeft: "-"+popWidth+"px"},1200,"linear",
         function(){ $(popOut).width($("#cap").width() + "px"); }        
      );
      isExtended = 0;     
       document.getElementById('open').src = '/images/slide-button.gif';
   }

   function checkSB() {
    
        var mode = readCookie('SB');
        if(mode == null){
            createCookie('SB',0,1);
            mode = 0;
        }
    
        if(mode == 1){
            openAd();
        }
    
    }

   $("#open").click(function() {
      if(isExtended == 0){
        openAd();
      }
      else {
        closeAd();
      }
      
       createCookie('SB',isExtended,1);      
      
        return false; 
   });   
   
  
	// check sidebar cookie
    checkSB();     
   
			
	$(".play").bind("click",function(){
		var $this = $(this);
		var cnt = parseInt($("#flipcnt"+$this.attr("id")).html(),10) + 1;
		$("#flipcnt"+$this.attr("id")).flip({
			direction: 'tb',
			content: cnt,
			color: 'yellow'
		})
	});						
				
});

function pad(number, length) {
   
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;

}


// CHECK VALID EMAIL //
function isEmailAddress (string) {
            var addressPattern = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
            return addressPattern.test(string);
}

// CHECK SUBSCRIPTION //
function subscription(){

    var email = $('#email').val();
    if(email==''){
        alert("To subscribe to free email updates, please supply a valid email address and try again.");
    }
    else{
        if (!isEmailAddress(email)) {
            alert("The email address you supplied appears to be invalid.\n\nPlease check and try again.");
        }
        else{
            $('#email').val('Please Wait...');
            makeRequest('/cgi-bin/subscription.pl', 'FA=SUB&VALUE='+escape(email), disp_subscription);
        }
        
    }              
 
}

function disp_subscription(txt){
    if(txt == 1){
        window.location.href = '/thanks.html';
    }
    else{
        window.location.href = '/error.html';
    }
}

function joinDMO(){
    
    $('#leftsec').html('<h2 class="clear">Please Wait...</h2>');
    makeRequest('/cgi-bin/join.pl', 'FA=JOIN', disp_joinDMO);    
    
}

function disp_joinDMO(txt){
    
    $('#leftsec').html(txt);    

}

function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + "=" + escape(value) +
	((expires) ? "; expires=" + expires : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
	document.cookie = curCookie;
}
	
function set_dl(){
// date 1 day in future
	var ex = new Date();
	ex.setTime(ex.getTime() + (1*24*60*60*1000));
	ex = ex.toGMTString();
	//set nobug cookie
	setCookie('DMO_DOWNLOAD', "1", ex, "/", "dance-music.org");
	
	//hide noscript tag from opera
	if(document.getElementById('noscript')){
	    document.getElementById('noscript').style.display='none';
	}
	
    // show popout menu
    document.getElementById('popout').style.visibility='visible';
	
}

// Show Thumbnail Larger Image
function showThumb(e,img,hand,art,tit,gen){        
    
    if(hand == 'l'){
        document.getElementById('thumb').style.left=e.clientX-280+'px';
    }
    else{
        document.getElementById('thumb').style.left=e.clientX+30+'px';
    }

    if (document.all) {
        var top = document.documentElement.scrollTop;
        document.getElementById('thumb').style.top=e.clientY+top-100+'px';
    }
    else {
        var top = window.pageYOffset; 
        document.getElementById('thumb').style.top=e.clientY+top-100+'px';
    }

    var text = '<h6><span class="blue">' + tit + '</span><br />(' + gen + ')</h6>';
       
    text += '<img src="/images/covers/'+img+'"><h6 style="padding-bottom:6px;"><span class="blue">' + art + '</span></h6>';    

    document.getElementById('thumb').innerHTML = text;
    
    document.getElementById('thumb').style.visibility='visible'; 

} 

// Hide Larger Image
function hideThumb(){ 
      document.getElementById('thumb').innerHTML = '<img src="/images/wait.gif">'; 
      document.getElementById('thumb').style.visibility='hidden'; 
}        


// SideBar Cookie	
function createCookie(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=/";
}

function readCookie(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;
}

    

function showWait(ison,tagid,pause){
    if(ison == 1){
        document.getElementById(tagid).style.display='block';
        setTimeout('showWait(0,\''+tagid+'\');', pause);
    }
    else{
        document.getElementById(tagid).style.display='none';
    }
    
}

/* Sign Up */

function limitText(id,max) {

    var chkField = $('#'+id);
        
    if (chkField.val().length > max) {
		chkField.val(chkField.val().substring(0, max));
    }

}

function checkVal(id){    
    
    var chkField = $('#'+id);
  
    
    if(id == 'artistemail'){
        chkField.val(chkField.val().replace(/[^0-9a-z\.\@\-\_]/gi, ''));	
    }
    else if(id == 'artistbio'){
        chkField.val(chkField.val().replace(/[^0-9 a-z\'\\\/\:\;\-\+\.\?\!\*\(\)\_\& \,\r\n]/gi, ''));
    }
    else if(id == 'artistpassword'){
       chkField.val(chkField.val().replace(/[^0-9 a-z\_\-\.\!]/gi, ''))
    } 
    else if(id == 'message'){
       chkField.val(chkField.val().replace(/[^0-9 a-z\_\-\.\!\@\'\&\r\n\_\+\;\:\,\r \n\?\(\)]/gi, ''))
    }     
    else{
        chkField.val(chkField.val().replace(/[^0-9 a-z\'\\\/\:\;\-\+\.\?\!\*\(\)\_\& \,]/gi, ''));        
    }
    
}

function checkJoin(){

    var msg = '';
    
    // artist
    if($('#artistname').val() == ''){
        msg += 'Artist\n';
    }
    
    // fullname
    if($('#artistfullname').val() == ''){
        msg += 'Fullname(s)\n';
    }    
    
    // DOB
    if($('#artistDOB').val() == ''){
        msg += 'Date of Birth\n';
    }   
   
    // Star Sign
    if($('#artistsign').val() == ''){
        msg += 'Star sign\n';
    } 
    
    // Nationality
    if($('#artistnationality').val() == ''){
        msg += 'Nationality\n';
    } 
    
    // Email
    if($('#artistemail').val() == ''){
        msg += 'Email\n';
    }
    else if(!isEmailAddress($('#artistemail').val())){
        msg += 'Invalid email\n';
    }
    
    
    // Password
    if($('#artistpassword').val() == ''){
        msg += 'Password\n';
    }   
    
    // Bio
    if($('#artistbio').val() == ''){
        msg += 'Tell us about yourself\n';
    } 
    
    // Photo
    if($('#artistphoto').val() == ''){
        msg += 'Artist photo\n';
    }     
    else {
        var ext = $('#artistphoto').val().split('.').pop().toLowerCase(); 
        if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) { msg += 'Invalid File Type -> Only (jpg/gif/png) Allowed!\n';}
    }
        
 
    if(msg != ''){
        alert('Please ensure you complete the following...\n\n'+msg);
    }
    else{
        $('#AUTH').val('1736yehftr75642jd83');
        $('#FA').val('SIGNUP');
        $('#leftsec').toggle('slow');          
        $('#joinform').submit();        
    }
    
}


function showAns(id){
    
    $('.hide').fadeOut('fast');
    $('.hide2').fadeOut('fast');     
    $('#A'+id).toggle('slow');
  
}


// Show Help 
function showHelp(e,txt){        
    
    document.getElementById('thumb2').style.left=e.clientX+30+'px';

    if (document.all) {
        var top = document.documentElement.scrollTop;
        document.getElementById('thumb2').style.top=e.clientY+top-50+'px';
    }
    else {
        var top = window.pageYOffset; 
        document.getElementById('thumb2').style.top=e.clientY+top-50+'px';
    }
    

    document.getElementById('thumb2').innerHTML = txt;
    
    document.getElementById('thumb2').style.visibility='visible'; 

} 

// Hide Help
function hideHelp(){ 
      document.getElementById('thumb2').innerHTML = '<img src="/images/wait.gif">'; 
      document.getElementById('thumb2').style.visibility='hidden'; 
}


// send artist message
function send_message(id) {
    
    var mess = $('#message').val();
    
    if(mess == ''){
        alert('Please enter your message.');
    }
    else{
        makeRequest('/cgi-bin/send_message.pl', 'FA=MSG&AUTH=sdjsdf782348234jsdfjksdf923332fe&MESS='+escape(mess)+'&ID='+id, disp_send_message);
    }
    
}

function disp_send_message(txt){
    
    if(txt == 1){
        $('#message').val('');
        $('#contact_artist').toggle();
        alert('Your message has been sent!');
    }
    else {
        alert('Error sending message, please try again!');
    }
    
}

    

