// Globals
galleryRequest = null;
contactMeRequest = null;

slideShow = new SlideShow();



// ==========================================================
// ==========================================================
//
// GALLERIES
//
// ==========================================================
// ==========================================================


function topFive_onclick()
{
    /*
    Callback for when the user clicks TOP 5.
    */
    
    slideShow.stop();
    
    // Create and run the request
    galleryRequest = new XmlRequest( 'GET', 'getimages.php', 'src=img_topfive&count=5', gallery_onchange );
    galleryRequest.run();
}

function fullGallery_onclick()
{
    /*
    Callback for when the user clicks FULL GALLERY.
    */
    
    slideShow.stop();
    
    // Create and run the request
    galleryRequest = new XmlRequest( 'GET', 'getimages.php', 'src=img_full&count=0', gallery_onchange );
    galleryRequest.run();
}



function gallery_onchange()
{
    /*
    Callback for when the server returns after
    the user clicked TOP 5 or FULL GALLERY.
    */
    
    if( galleryRequest.request.readyState == 4 )
    {
        if( galleryRequest.request.status != 200 ) {
            var alertText = [
                'Could not get the gallery data.\nPlease try again later.\n',
                'Status: ' + galleryRequest.request.status + '\n',
                'Response:',
                galleryRequest.request.responseText
            ];
            alert( alertText.join('\n') );
        
        } else {
            // Get the xml output.
            // For some reason, I'm not getting a proper xml document.
            // I have to make assumptions about the return value.
            var xmlResponse = galleryRequest.request.responseXML;
            var imgTags = xmlResponse.getElementsByTagName( 'img' );
            var imgCount = imgTags.length;
            
            // Set the global gallery array
            imgPaths = new Array( imgCount );
            
            // Preload the images
            var imgTag, imgText, imgPath;
            for( var i=0; i<imgCount; i++ )
            {
                imgTag = imgTags[i];
                imgText = imgTag.firstChild;
                imgPath = imgText.data;
                imgPaths[i] = imgPath;
            }
            
            slideShow.setImgPaths( imgPaths );
            slideShow.start();
        }
    }
}




function slideIt()
{
    if( runSlide == true ) {
        var imgPath = galleryImages[step];
        
        var imgTag = document.createElement( 'img' );
        imgTag.src = imgPath;
        imgTag.className = 'imgGallery';
        
        var aTag = document.createElement( 'a' );
        aTag.className = 'aGallery';
        aTag.href = 'viewone.php?imgpath=' + imgPath;
        aTag.appendChild( imgTag );
        
        var divTransientZone = document.getElementById( 'divTransientZone' );
        
        // Because of some weird shit with IE,
        // it's safer to delete the child nodes one by one.
        while( divTransientZone.hasChildNodes() )
        {
            divTransientZone.removeChild( divTransientZone.lastChild );
        }
        
        divTransientZone.appendChild( aTag );
        
        
        if ( step < galleryImages.length-1 ) {
            step++;
        } else {
            step = 0;
        }
        
        setTimeout( "slideIt()", 2400 );
    }
}











// ==========================================================
// ==========================================================
//
// ABOUT ME
//
// ==========================================================
// ==========================================================


function aboutMe_onclick()
{
    /*
    Callback for when the user clicks ABOUT ME.
    */
    
    slideShow.stop();
    
    var text = [
        '<a class="linksAboutMe" target="_blank" href="http://www.modelmayhem.com/1898950">modelmayhem</a><br>',
        '<a class="linksAboutMe" target="_blank" href="http://www.flickr.com/photos/bernardlebel/">flickr</a><br>',
        '<a class="linksAboutMe" target="_blank" href="http://www.imdb.com/name/nm1009812/">imdb</a><br>',
        "<br><br><br>",
        
        "STYLE AND GOALS",
        "<br><br>",
        "Although I'm interested in boudoir and glamour photographie, I found that I'm leaning more toward unconventional themes,",
        "such as fetish (that is, latex), erotic, gothic, dark and gloomy things.",
        "<br><br>",
        "The primary quality I'm trying to achieve is sensuality.",
        "The actual theme doesn't matter, there has to be a strong sense of sensuality and vulnerability.",
        "The pose, facial expression, lighting, background (if any), and situation, should all contribute to those qualities.",
        "<br><br><br><br>",
        
        "BACKGROUND",
        "<br><br>",
        "Born in 1975, I'm originally from Montreal, Canada.",
        "I'm French Canadian, or more specifically, Québécois.",
        "I moved to Los Angeles in May 2008 to work for DreamWorks Animation, where I'm Technical Director.",
        "<br><br>",
        "I have been doing 3D animation since 2000.",
        "My credits include How To Train Your Dragon, Rise Of The Guardians, Scared Shrekless, Fantastic Four,",
        "The Magic Roundabout (aka Doogal in the US), plus a whole bunch of TV and DVD projects.",
        "<br><br>",
        "Prior to that, I was a graphic designer for 2 years, I studied graphic design in college (college in Québec is different than the US, it's not university).",
        "<br><br><br><br>",
        
        "ENTER PHOTOGRAPHIE",
        "<br><br>",
        'I "discovered" photographie in April or May 2010.',
        "I got my first DSLR, a Canon 550D (aka 2Ti) with a 50mm f/1.4 lens, and there was no turning back.",
        "Photographie has been a growing passion since that day.",
        "<br><br>",
        "Initially I wanted to spend $1200, but in less than a year I ended up spending like $10,000:",
        "a Canon 5D Mark II, a Canon 24-70mm f/2.8 lens, a new computer, TONS of accessories, strobes, umbrellas, back drops, and so on.",
        "<br><br>",
        "I started shooting co-workers and the neighbourhood, but it didn't take long before I started shooting models.",
        "At the advice of a friend, I joined meetup.com groups that did photo shoots with models at a low cost.",
        "That got me started.",
        "I did a bunch of photo shoots with these guys, and learned a ton.",
        "<br><br>",
        "But I was frustrated with the group approach, and I got all the necessary equipment to do photo shoots at home.",
        "So I started shooting models at my place or carrying my equipment on location.",
        "It's been extremely gratifying.",
        "<br><br>",
        "I enjoy photographing models, but also food, nature, cars, concerts, and events.",
        "<br><br><br><br>",
        
        "INSPIRATION",
        "<br><br>",
        "My top artists are H.R. Giger, Tim Burton, Hans Zimmer, Brian Williams (aka Lustmord), Peter Andersson, Billy Lane and the Martin Brothers.",
        "<br>",
        "My favorite movies are Sleepy Hollow, the first Matrix, Dark City, Ali, Once Upon A Time In The West, Dances With Wolves.",
        "<br>",
        "In photographie, Phillip Ritchie and Jefferson Peak are artists I look up to.",
        "<br><br>",
        "In general, I prefer dark, gloomy, and moody artwork. I like beautiful and surreal light.",
        "<br><br><br><br>",
        
        '<img src="me.jpg" style="border: 0px; padding: 0px">'
    ];
    
    var pAboutMe = document.createElement( 'p' );
    pAboutMe.innerHTML = text.join( ' ' );
    
    var tdAboutMe1 = document.createElement( 'td' );
    tdAboutMe1.className = 'tdAboutMe1';
    tdAboutMe1.appendChild( pAboutMe );
    
    var tdAboutMe2 = document.createElement( 'td' );
    tdAboutMe2.className = 'tdAboutMe2';
    
    var trAboutMe = document.createElement( 'tr' );
    trAboutMe.appendChild( tdAboutMe1 );
    trAboutMe.appendChild( tdAboutMe2 );
    
    var tbody = document.createElement( 'tbody' );
    tbody.appendChild( trAboutMe );
    
    var tableAboutMe = document.createElement( 'table' );
    tableAboutMe.id = 'tableAboutMe';
    tableAboutMe.appendChild( tbody );
    
    var divAboutMe = document.createElement( 'div' );
    divAboutMe.id = 'divAboutMe';
    divAboutMe.appendChild( tableAboutMe );
    
    var tZone = document.getElementById( 'divTransientZone' );
    tZone.innerHTML = '';
    tZone.appendChild( divAboutMe );
}












// ==========================================================
// ==========================================================
//
// CONTACT ME
//
// ==========================================================
// ==========================================================


function contactMe_onclick()
{
    /*
    Callback for when the user clicks CONTACT ME.
    */
    
    slideShow.stop();
    
    // Top spacer
    var tdTop = document.createElement( 'td' );
    tdTop.className = 'contactMeTop';
    
    var trTop = document.createElement( 'tr' );
    trTop.appendChild( tdTop );
    
    // Email
    var imgEmail = document.createElement( 'img' );
    imgEmail.src = 'img_index/contactme_email.png';
    imgEmail.className = 'imgLabel';
    
    var tdEmailLabel = document.createElement( 'td' );
    tdEmailLabel.className = 'tdLabel';
    tdEmailLabel.appendChild( imgEmail );
    
    var inputEmail = document.createElement( 'input' );
    inputEmail.id = 'contactMeEmail';
    inputEmail.name = 'email';
    inputEmail.type = 'text';
    inputEmail.maxlength = 60;
    inputEmail.className = 'input';
    
    var tdEmailInput = document.createElement( 'td' );
    tdEmailInput.className = 'tdInput';
    tdEmailInput.appendChild( inputEmail );
    
    var trEmail = document.createElement( 'tr' );
    trEmail.appendChild( tdEmailLabel );
    trEmail.appendChild( tdEmailInput );
    
    // Subject
    var imgSubject = document.createElement( 'img' );
    imgSubject.src = 'img_index/contactme_subject.png';
    imgSubject.className = 'imgLabel';
    
    var tdSubjectLabel = document.createElement( 'td' );
    tdSubjectLabel.className = 'tdLabel';
    tdSubjectLabel.appendChild( imgSubject );
    
    var inputSubject = document.createElement( 'input' );
    inputSubject.type = 'text';
    inputSubject.id = 'contactMeSubject';
    inputSubject.name = 'subject';
    inputSubject.maxlength = 100;
    inputSubject.className = 'input';
    
    var tdSubjectInput = document.createElement( 'td' );
    tdSubjectInput.className = 'tdInput';
    tdSubjectInput.appendChild( inputSubject );
    
    var trSubject = document.createElement( 'tr' );
    trSubject.appendChild( tdSubjectLabel );
    trSubject.appendChild( tdSubjectInput );
    
    // Body
    var imgMsg = document.createElement( 'img' );
    imgMsg.src = 'img_index/contactme_msg.png';
    imgMsg.className = 'label';
    
    var tdMsgLabel = document.createElement( 'td' );
    tdMsgLabel.className = 'tdMsgLabel';
    tdMsgLabel.appendChild( imgMsg );
    
    var inputMsg = document.createElement( 'textarea' );
    inputMsg.id = 'contactMeMsg';
    inputMsg.name = 'msg';
    inputMsg.className = 'inputMsg';
    
    var tdMsgInput = document.createElement( 'td' );
    tdMsgInput.className = 'tdMsgInput';
    tdMsgInput.appendChild( inputMsg );
    
    var trMsg = document.createElement( 'tr' );
    trMsg.appendChild( tdMsgLabel );
    trMsg.appendChild( tdMsgInput );
    
    // Send
    var tdSendLabel = document.createElement( 'td' );
    tdSendLabel.className = 'tdSend';
    
    var inputSend = document.createElement( 'input' );
    inputSend.type = 'image';
    inputSend.value = 'SEND';
    inputSend.src = 'img_index/contactme_send.png';
    inputSend.className = 'imgSend';
    inputSend.onclick = function(){return(send_onclick());};
    
    var tdSendButton = document.createElement( 'td' );
    tdSendButton.className = 'tdSendButton';
    tdSendButton.appendChild( inputSend );
    
    var trSend = document.createElement( 'tr' );
    trSend.appendChild( tdSendLabel );
    trSend.appendChild( tdSendButton );
    
    // Finalize the table
    var tbody = document.createElement( 'tbody' );
    tbody.id = 'tbodyContactMe';
    tbody.appendChild( trTop );
    tbody.appendChild( trEmail );
    tbody.appendChild( trSubject );
    tbody.appendChild( trMsg );
    tbody.appendChild( trSend );
    
    var tableContactMe = document.createElement( 'table' );
    tableContactMe.id = 'tableContactMeId';
    tableContactMe.appendChild( tbody );
    
    var tZone = document.getElementById( 'divTransientZone' );
    tZone.innerHTML = '';
    tZone.appendChild( tableContactMe );
}




function send_onclick()
{
    /*
    Callback when the user clicks the SEND button.
    */
    
    var inputEmail = document.getElementById( 'contactMeEmail' );
    var inputSubject = document.getElementById( 'contactMeSubject' );
    var inputMsg = document.getElementById( 'contactMeMsg' );
    
    if( (inputEmail == null) | (inputSubject == null) | (inputMsg == null) ) {
        alert( 'Sorry, but for some reason this page is missing something, your email cannot be sent. Please refresh the page and try again.' );
        return;
    }
    
    var email = inputEmail.value;
    var subject = inputSubject.value;
    var msg = inputMsg.value;
    
    // Make sure all fields have a value
    if ( email == '' ) { 
        alert( 'Please enter an email address' );
        return;
    } else if ( subject == '' ) {
        alert( 'Please enter a subject line' );
        return;
    } else if ( msg == '' ) {
        alert( 'Please enter a message' );
        return;
    }
    
    // If user passed illegal characters in email, abort
	badEmailChars = new Object();
	badEmailChars['/'] = '/';
	badEmailChars['!'] = '!';
	badEmailChars['#'] = '#';
	badEmailChars['%'] = '%';
	badEmailChars['&'] = '&';
	badEmailChars['='] = '=';
	badEmailChars['¤'] = '¤';
	badEmailChars['{'] = '{';
	badEmailChars['}'] = '}';
	badEmailChars['¬'] = '¬';
	badEmailChars['¨'] = '¨';
	badEmailChars['`'] = '`';
	badEmailChars['~'] = '~';
	badEmailChars[','] = ',';
	badEmailChars["'"] = "'";
	badEmailChars['"'] = '"';
	badEmailChars['<'] = '<';
	badEmailChars['>'] = '>';
	badEmailChars['é'] = 'é';
	badEmailChars['É'] = 'É';
	badEmailChars[';'] = ';';
	badEmailChars[':'] = ':';
	badEmailChars['è'] = 'è';
	badEmailChars['È'] = 'È';
	badEmailChars['à'] = 'à';
	badEmailChars['À'] = 'À';
	badEmailChars['ç'] = 'ç';
	badEmailChars['Ç'] = 'Ç';
	badEmailChars['|'] = '\\|';
	badEmailChars['$'] = '\\$';
	badEmailChars['?'] = '\\?';
	badEmailChars['^'] = '\\^';
	badEmailChars['*'] = '\\*';
	badEmailChars['('] = '\\(';
	badEmailChars[')'] = '\\)';
	badEmailChars['+'] = '\\+';
	badEmailChars['\\'] = '\\\\';
	badEmailChars['['] = '\\[';
	badEmailChars[']'] = '\\]';
	
	var badChar, regExp;
    for( badChar in badEmailChars )
    {
		badCharRegExp = badEmailChars[badChar];
		regExp = new RegExp( badCharRegExp, 'gi' );
		
		if( regExp.test(email) ) {
			alert( 'The email address contains an illegal character ( ' + badChar + ' )' );
			return;
		}
    }
    
	// For subject and email, we're more permissive and we simply replace
	// suspicious characters or tokens with something safe.
    var replaceMap = new Object();
	replaceMap['FileSystemObject'] = '';
	replaceMap['wscript'] = '';
    replaceMap['system'] = 's-ystem';
	replaceMap['exec'] = 'e-xec';
	replaceMap['eval'] = 'e-val';
	replaceMap['run'] = 'r-un';
	replaceMap['open'] = 'o-pen';
	replaceMap['file'] = 'f-ile';
	
	var badToken, newToken;
	for( badToken in replaceMap )
	{
		newToken = replaceMap[badToken];
		regExp = new RegExp( badToken, 'gi' );
		
		subject = subject.replace( regExp, newToken );
		msg = msg.replace( regExp, newToken );
	}
    
    // Put together request parameters
    var sendParameters = [
        'email=' + email,
        'subject=' + subject,
        'msg=' + msg
    ];
    sendParameters = sendParameters.join( '&' );
    
    // Create and run the request
    contactMeRequest = new XmlRequest( 'POST', 'sendmail.php', sendParameters, send_onchange );
    contactMeRequest.run();
}





function send_onchange()
{
    /*
    Callback for when the server returns after the user clicks SEND.
    */
    
    if( contactMeRequest.request.readyState == 4 )
    {
        if( contactMeRequest.request.status != 200 ) {
            var alertText = [
                'There was a problem sending your message.\nPlease try again later.\n',
                'Status: ' + contactMeRequest.request.status + '\n',
                'Response:',
                contactMeRequest.request.responseText
            ];
            alert( alertText.join('\n') );
        
        } else {
            // Get the xml output.
            // For some reason, I'm not getting a proper xml document.
            // I have to make assumptions about the return value.
            var xmlResponse = contactMeRequest.request.responseXML;
            var contentNode = xmlResponse.documentElement;
            var resultNode = contentNode.lastChild;
            var result = resultNode.firstChild.data;
            
            if( result == 'failed' ) {
                var alertText = [
                    'There was a problem sending your message.\nPlease try again later.\n',
                    'Response: ',
                    contactMeRequest.request.responseText
                ];
                alert( alertText.join('\n') );
            
            } else {
                // Top spacer
                var tdTop = document.createElement( 'td' );
                tdTop.className = 'contactMeTop';
                
                var trTop = document.createElement( 'tr' );
                trTop.appendChild( tdTop );
                
                // Text row
                var pResult = document.createElement( 'p' );
                pResult.className = 'pEmailResult';
                pResult.innerHTML = 'Your message was sent. Thank you.';
                
                var tdResult = document.createElement( 'td' );
                tdResult.className = 'tdEmailResult';
                tdResult.appendChild( pResult );
                
                var trResult = document.createElement( 'tr' );
                trResult.appendChild( tdResult );
                
                // Modify the contactMe table
                var tbody = document.getElementById( 'tbodyContactMe' );
                
                // Due to some weird thing with IE,
                // we can't simply do tbody.innerHTML = ''
                // We have to remove the child nodes one by one.
                while( tbody.hasChildNodes() )
                {
                    tbody.removeChild( tbody.lastChild );
                }
                
                tbody.appendChild( trTop );
                tbody.appendChild( trResult );
            }
        }
    }
    
    return( false );
}












// ==========================================================
// ==========================================================
//
// HELPERS
//
// ==========================================================
// ==========================================================



function XmlRequest( requestType, url, sendParameters, stateChangeFunc )
{
	/*
    Create a new XMLHttpRequest object 
    appropriate for the browser.
    
    :Parameters:
        requestType (string) 
            The type of request: GET, POST, HEAD 
        url (string) 
            The requested url 
        stateChangeFunc (function) 
            The callback function for the 
            onload/onreadystatechange attribute.
    
    :Return:
        XMLHttpRequest
    */
    
    this.requestType = requestType;
    this.url = url;
    this.sendParameters = sendParameters;
    this.stateChangeFunc = stateChangeFunc;
    
    // If we're doing a GET request,
    // set the send parameters to null,
    // and instead pass the send parameters via the url.
    if( requestType == 'GET' ) {
        if( (sendParameters != null) && (sendParameters != '') ) {
            this.url = url + '?' + sendParameters;
        }
        this.sendParameters = null;
    }
    
    this.request = null;
    this.revisions = [
        'MSXML6.DOMDocument',
        'MSXML5.DOMDocument',
        'MSXML4.DOMDocument',
        'MSXML3.DOMDocument',
        'MSXML2.DOMDocument',
        'Msxml2.XMLHTTP',
        'MSXML.DOMDocument',
        'Microsoft.XmlDom',
        'Microsoft.XMLHTTP',
    ];
    
    
    //-------------- CREATE REQUEST --------------//
    
    // firefox, opera, explorer 8+
    if( window.XMLHttpRequest ) {
        this.request = new XMLHttpRequest();
    }
    // pre explorer 8
    else if( window.ActiveXObject )
    {
        // Loop through all revisions of the xml object
        var revision;
        for( var r=0; r < this.revisions.length; r++ )
        {
            revision = this.revisions[r];
            
            // Try to create the xml object using this revision
            try {
                if( (this.request = new ActiveXObject(revision)) ) {
                  break;
                }
            }
            catch( ignored ) {
            }
        }
    }


    //-------------- METHODS --------------//
    
    this.run = function()
    {
        /*
        Run the xml request object.
        */
        
        if( this.request != null ) {
            this.request.onreadystatechange = this.stateChangeFunc;
            this.request.open( this.requestType, this.url, true );
            
            if( this.requestType == 'POST' ) {
                this.request.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded' );
                this.request.setRequestHeader( 'Content-length', this.sendParameters.length );
                this.request.setRequestHeader( 'Connection', 'close' );
            }
            
            this.request.send( this.sendParameters );
        }
        return;
    }
}









function SlideShow()
{
    this.run = false;
    this.step = 0;
    this.maxStep = 0;  // typically this.imgCount -1
    this.timeOut = 1;
    this.isNew = true; // this is true only at creation time
    this.imgPaths = new Array();
    this.imgCount = 0;
    
    this.setImgPaths = function( imgPaths )
    {
        this.imgPaths = imgPaths;
        this.imgCount = imgPaths.length;
        this.step = 0;
        this.maxStep = 0;
        
        if( this.imgCount > 0 ) {
            this.maxStep = this.imgCount -1;
        }
		
		// Preload images
		var preloadObj = new Image();
		for( var i=0; i<this.imgCount; i++ ) {
			preloadObj.src = this.imgPaths[i];
		}
    }
    
    this.start = function() {
        this.run = true;
        this.timeOut = 2400;
        
        if( this.isNew == true ) {
            this.step = 0;
            this.isNew = false;
            this.slideIt();
        }
    }
    
    this.stop = function() {
        this.run = false;
        this.timeOut = 1;
        this.clearTransientZone();
    }
    
    this.slideIt = function()
    {
        if( this.run == true ) {
            var imgPath = this.imgPaths[this.step];
            
            var imgTag = document.createElement( 'img' );
            imgTag.src = imgPath;
            imgTag.className = 'imgGallery';
            
            var aTag = document.createElement( 'a' );
            aTag.className = 'aGallery';
            aTag.href = 'viewone.php?imgpath=' + imgPath;
            aTag.appendChild( imgTag );
            
            this.clearTransientZone();
            var divTransientZone = document.getElementById( 'divTransientZone' );
            divTransientZone.appendChild( aTag );
            
            if ( this.step < this.maxStep ) {
                this.step++;
            } else {
                this.step = 0;
            }
        }
        
        setTimeout( "slideShow.slideIt()", this.timeOut );
    }
    
    this.clearTransientZone = function()
    {
        var divTransientZone = document.getElementById( 'divTransientZone' );
        
        // Because of some weird shit with IE,
        // it's safer to delete the child nodes one by one.
        while( divTransientZone.hasChildNodes() )
        {
            divTransientZone.removeChild( divTransientZone.lastChild );
        }
    }
}
